/* Solution to Evolution by Mees * * Uses Prim's algorithm, for run time O(n log(n)). * * Expected answer: ACCEPTED. * */ #include #include #include using namespace std; int main() { int n, k; cin >> n >> k; vector dna(n); for(int i = 0; i < n; i++) cin >> dna[i]; vector intree(n, false); vector> dist(n, vector(n, 0)); int besti = -1; int bestj = -1; int best_dist = 100000; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(i == j) continue; dist[i][j] = 0; for(int c = 0; c < k; c++) { if(dna[i][c] != dna[j][c]) dist[i][j]++; } if(dist[i][j] < best_dist) { besti = i; bestj = j; best_dist = dist[i][j]; } } } int weight = 0; intree[besti] = true; intree[bestj] = true; vector> edges; edges.push_back({besti, bestj}); weight += dist[besti][bestj]; priority_queue>> q; for(int i : {besti, bestj}) { for(int j = 0; j < n; j++) { if(!intree[j]) { q.push(make_pair(-dist[i][j], make_pair(i, j))); } } } while(!q.empty()) { auto top = q.top(); q.pop(); int i = top.second.second; if(intree[i]) continue; intree[i] = true; edges.push_back({top.second.first, i}); weight += -top.first; for(int j = 0; j < n; j++) { if(!intree[j]) { q.push(make_pair(-dist[i][j], make_pair(i, j))); } } } cout << weight << '\n'; for(auto e : edges) cout << e.first << ' ' << e.second << '\n'; return 0; }