/* -*- coding: utf-8 -*- * * 1166.cc: No.1166 NADA DNA - yukicoder */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_N = 1000; const int MAX_M = MAX_N * (MAX_N - 1) / 2; const int MAX_L = 50; /* typedef */ struct Edge { int d, i, j; Edge() {} Edge(int _d, int _i, int _j): d(_d), i(_i), j(_j) {} bool operator<(const Edge &e) const { return d < e.d; } }; struct UFT { int links[MAX_N], ranks[MAX_N], sizes[MAX_N]; UFT() {} void init(int n) { for (int i = 0; i < n; i++) links[i] = i, ranks[i] = sizes[i] = 1; } int root(int i) { int i0 = i; while (links[i0] != i0) i0 = links[i0]; return (links[i] = i0); } int rank(int i) { return ranks[root(i)]; } int size(int i) { return sizes[root(i)]; } bool same(int i, int j) { return root(i) == root(j); } int merge(int i0, int i1) { int r0 = root(i0), r1 = root(i1), mr; if (r0 == r1) return r0; if (ranks[r0] == ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; ranks[r0]++; mr = r0; } else if (ranks[r0] > ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; mr = r0; } else { links[r0] = r1; sizes[r1] += sizes[r0]; mr = r1; } return mr; } }; /* global variables */ char gs[MAX_N][MAX_L + 4]; Edge es[MAX_M]; UFT uft; /* subroutines */ inline int hdist(char s[], char t[], int l) { int d = 0; for (int i = 0; i < l; i++) if (s[i] != t[i]) d++; return d; } /* main */ int main() { int n, l; scanf("%d%d", &n, &l); for (int i = 0; i < n; i++) scanf("%s", gs[i]); int m = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) es[m++] = Edge(hdist(gs[i], gs[j], l), i, j); sort(es, es + m); uft.init(n); int sum = 0; for (int i = 0; i < m; i++) { Edge &e = es[i]; if (! uft.same(e.i, e.j)) { uft.merge(e.i, e.j); sum += e.d; } } printf("%d\n", sum); return 0; }