#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <set>
#include <random>
#include <algorithm>
#include <ctime>

using namespace std;

const int BASE = 26;
const int POPULATION_SIZE = 500;  // 种群大小
const int MAX_GENERATIONS = 1000;  // 最大代数
const double MUTATION_RATE = 0.03;  // 变异率

random_device rd;
mt19937 generator(rd());

// 一个个体
struct Individual {
    vector<int> keymap; // 染色体，字根布局 
    int fitness; // 个体的适应度

    Individual() : fitness(0) {}
    Individual(const vector<vector<int>>& cfb);
    void calc_fitness(const vector<vector<int>>& cfb);
    Individual mate(const Individual& partner) const;
    void mutate();
};

set<int> extract_unique_numbers(const vector<vector<int>>& cfb) {
    set<int> unique_numbers;
    for (const auto& row : cfb) {
        unique_numbers.insert(row.begin(), row.end());
    }
    return unique_numbers;
}

Individual::Individual(const vector<vector<int>>& cfb) {
    set<int> root = extract_unique_numbers(cfb);
    uniform_int_distribution<int> distribution(1, BASE);
    keymap.resize(root.size());
    for (size_t i = 0; i < keymap.size(); i++) {
        keymap[i] = distribution(generator);
    }
    calc_fitness(cfb);
}

inline void Individual::calc_fitness(const vector<vector<int>>& cfb)
{
	fitness = 0;
	vector<bool> duplication(BASE * BASE * BASE + BASE * BASE + BASE, false);
	for (const auto& zi : cfb) {
		int code = 0;
		for (int j = zi.size()-1; j >= 0; j--) {
			code = code * BASE + keymap[zi[j]];
//			if (duplication[code] && j != 0) {
//				continue;
//			} else if(duplication[code]&&j==0){
//				fitness++;
//			} else{
//				duplication[code]=true;
//				break;
//			}
		}
		if (duplication[code]) {
			fitness--;
		} else{
			duplication[code]=true;
		}
	} 
}

Individual Individual::mate(const Individual& partner) const {
    Individual child;
    uniform_int_distribution<int> distribution(0, 1);
    child.keymap.resize(keymap.size());
    for (size_t i = 0; i < keymap.size(); i++) {
        child.keymap[i] = distribution(generator) ? keymap[i] : partner.keymap[i];
    }
    return child;
}

void Individual::mutate() {
    uniform_real_distribution<> dis(0, 1);
    uniform_int_distribution<> key_dis(1, BASE);
    for (int& key : keymap) {
        if (dis(generator) < MUTATION_RATE) {
            key = key_dis(generator);
        }
    }
}

vector<vector<int>> read_cfb(const string& filename) {
    vector<vector<int>> cfb;
    ifstream file(filename);
    
    if (!file.is_open()) {
        cerr << "无法打开文件: " << filename << endl;
        return cfb;
    }
    
    string line;
    while (getline(file, line)) {
        vector<int> row;
        istringstream iss(line);
        string token;
        
        while (getline(iss, token, '\t')) {
            try {
                row.push_back(stoi(token));
            } catch (const invalid_argument& e) {
                cerr << "无法转换为整数: " << token << endl;
            } catch (const out_of_range& e) {
                cerr << "数字超出范围: " << token << endl;
            }
        }
        
        if (!row.empty()) {
            cfb.push_back(row);
        }
    }
    file.close();
    
    cout << "从 " << filename << " 读取了 " << cfb.size() << " 行数据。" << endl;
    
    return cfb;
}

// 主函数
int main() {
    string filename = "cfb.txt";
    vector<vector<int>> cfb = read_cfb(filename);

    // 初始化种群
    vector<Individual> population(POPULATION_SIZE, Individual(cfb));

    // 遗传算法主循环
    for (int generation = 0; /*generation < MAX_GENERATIONS*/; generation++) {
        // 计算适应度
        for (auto& individual : population) {
            individual.calc_fitness(cfb);
        }

        // 排序
        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {
            return a.fitness > b.fitness;
        });

        // 输出当前最佳解
        cout << "第 " << generation << " 代，最佳适应度: " << -population[0].fitness << endl;

        // 创建新一代
        vector<Individual> new_population;

        // 精英保留
        new_population.push_back(population[0]);
        new_population.push_back(population[1]);

        // 生成新个体
        while (new_population.size() < POPULATION_SIZE) {
            // 选择父母
            uniform_int_distribution<> select(0, POPULATION_SIZE / 2 - 1);
            Individual parent1 = population[select(generator)];
            Individual parent2 = population[select(generator)];

            // 交叉
            Individual child = parent1.mate(parent2);

            // 变异
            child.mutate();

            new_population.push_back(child);
        }

        // 更新种群
        population = new_population;
    }

    // 输出最终结果
    population[0].calc_fitness(cfb);
    cout << "最终结果：单字重码数 " << -population[0].fitness << endl;
    cout << "最佳键位映射：";
    for (int key : population[0].keymap) {
        cout << key << " ";
    }
    cout << endl;

    return 0;
}将代码改为遗传算法与退火算法相结合，并写上详细的注释