poj1789(MST)

思路:题目的意思就是求解一个源点到所有点距离之和最小,然后就是这个距离怎么计算就是两个字符串对应位置上不同字母的个数的多少,然后跑kruskal;

点击题目链接

/*****************************************
Author      :Crazy_AC(JamesQi)
Time        :2015
File Name   :
*****************************************/
// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
#define MEM(a,b) memset(a,b,sizeof a)
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
char s[2010][2010];
int F[2010];
int n;
struct Edge{
	int u,v,w;
	bool operator < (const Edge& b)const{
		return w < b.w;
	}
}E[2000 * 2000];
int get(int i,int j){
	int num = 0;
	for (int k = 0;k < strlen(s[i]);k++)
		if (s[i][k] != s[j][k]) num++;
	return num;
}
int cnt;
void Init(){
	cnt = 0;
	for (int i = 1;i <= n;i++){
		F[i] = i;
		for (int j = i + 1;j <= n;j++){
			int d = get(i,j);
			E[cnt].u = i;
			E[cnt].v = j;
			E[cnt].w = d;
			cnt++;
		}
	}
}
int Find(int x){
	if (F[x] == x) return x;
	else return F[x] = Find(F[x]);
}
void Kruskal(){
	sort(E,E + cnt);
	int sum = 0;
	int tol = 0;
	for (int i = 0;i < cnt;i++){
		int t1 = Find(E[i].u);
		int t2 = Find(E[i].v);
		if (t1 != t2){
			F[t1] = t2;
			sum += E[i].w;
			tol++;
		}
		if (tol == n - 1) break;
	}
	printf("The highest possible quality is 1/%d.\n",sum);
}


int main()
{	
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	while(scanf("%d",&n) != EOF && n){
		for (int i = 1;i <= n;i++)
			scanf("%s",s[i]);
		Init();
		Kruskal();
	}
	return 0;
}


你可能感兴趣的:(最小生成树,图论)