Skip to content

Instantly share code, notes, and snippets.

@lackofdream
Created April 18, 2015 01:30
Show Gist options
  • Save lackofdream/dc0235d2ed129075a6a8 to your computer and use it in GitHub Desktop.
Save lackofdream/dc0235d2ed129075a6a8 to your computer and use it in GitHub Desktop.
POJ1789
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <vector>
#include <fstream>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#include <string>
#define MAX(a,b) (a>b?a:b)
#define sd(x) scanf("%d",&x)
#define sdd(a,b) scanf("%d%d",&a,&b)
#define sddd(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define slflf(x,y) scanf("%lf%lf",&x,&y)
#define abs(x) (x<0?(-x):x)
#define MAX(a,b) (a>b?a:b)
#define MIN(a,b) (a<b?a:b)
using namespace std;
const int dsj_lenth = 2005;
char types[dsj_lenth][8];
int dsj[dsj_lenth];
void init()
{
for (int i=0; i<dsj_lenth; i++) dsj[i]=i;
}
int Find(int x)
{
return dsj[x]==x?x:dsj[x]=Find(dsj[x]);
}
inline void Union(int a,int b)
{
dsj[a]=b;
}
struct road
{
int u,v,w;
} r[dsj_lenth*dsj_lenth];
bool cmp(road a,road b)
{
return a.w<b.w;
}
int calculateDistance(char *a,char *b)
{
int cnt=0;
for (int i=0;i<7;i++) if(a[i]!=b[i]) cnt++;
return cnt;
}
int main()
{
int n;
while(~sd(n) && n)
{
getchar();
init();
int cnt=0;
for (int i=0;i<n;i++) gets(types[i]);
for (int i=0;i<n;i++)
{
for (int j=i+1;j<n;j++)
{
r[cnt].u=i;
r[cnt].v = j;
r[cnt++].w = calculateDistance(types[i],types[j]);
}
}
sort(r,r+cnt,cmp);
int ans=0,built=0;
for (int i=0;i<cnt;i++)
{
int fa = Find(r[i].u),fb = Find(r[i].v);
if (fa != fb)
{
Union(fa,fb);
built++;
ans += r[i].w;
}
if (built==n-1) break;
}
printf("The highest possible quality is 1/%d.\n",ans);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment