这个问题可以转化为:找一个连通图的最小生成树。
因为有自环,所以用prim算法会更简单一点。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
const int MAXN = 1000 + 2;
const int MAXL = 10 + 2;
int n, m, k;
ll w;
typedef struct Line{
int v; int weight;
Line(int a, int c){
v = a, weight = c;
}
bool operator < (const Line &rhs) const{
return weight > rhs.weight;
}
}Line;
int vis[MAXN];
char str[MAXN][MAXL];
vector<Line> g[MAXN];
int str_cnt(char *a, char *b, int len){
ll cnt = 0;
for(int i = 0; i < len; i++) if(a[i] != b[i]) cnt++;
return cnt;
}
bool check(int u, int v){
if(!vis[u]){
vis[u] = 1; return true;
}
if(!vis[v]){
vis[v] = 1; return true;
}
return false;
}
ll MP(){
ll res = m;
memset(vis, 0, sizeof(vis)); priority_queue<Line> q;
vis[1] = 1;
for(int i = 0; i < g[1].size(); i++){
int v = g[1][i].v; if(vis[v]) continue;
q.push(g[1][i]), q.push(Line(v, m));
}
while(!q.empty()){
Line cur = q.top(); q.pop();
int u = cur.v; ll weight = cur.weight;
if(vis[u]) continue;
res += weight; vis[u] = 1;
for(int i = 0; i < g[u].size(); i++){
int v = g[u][i].v;
if(vis[v]) continue;
q.push(g[u][i]), q.push(Line(v, m));
}
}
return res;
}
int main(void)
{
while(~scanf("%d%d%lld", &n, &m, &w)){
for(int i = 1; i <= n; i++) g[i].clear();
for(int i = 1; i <= n; i++) scanf("%s", str[i]);
for(int i = 1; i <= n; i++){
for(int j = i + 1; j <= n; j++){
g[i].push_back(Line(j, str_cnt(str[i], str[j], m) * w));
g[j].push_back(Line(i, str_cnt(str[i], str[j], m) * w));
}
}
printf("%lld\n", MP());
}return 0;
}