POJ 1789 Truck History
Posted zhchoutai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 1789 Truck History相关的知识,希望对你有一定的参考价值。
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 17275 | Accepted: 6623 |
Description
Today, ACM is rich enough to pay historians to study its history. One thing historians tried to find out is so called derivation plan -- i.e. how the truck types were derived. They defined the distance of truck types as the number of positions with different letters in truck type codes. They also assumed that each truck type was derived from exactly one other truck type (except for the first truck type which was not derived from any other type). The quality of a derivation plan was then defined as
where the sum goes over all pairs of types in the derivation plan such that to is the original type and td the type derived from it and d(to,td) is the distance of the types.
Since historians failed, you are to write a program to help them. Given the codes of truck types, your program should find the highest possible quality of a derivation plan.
Input
Output
Sample Input
4 aaaaaaa baaaaaa abaaaaa aabaaaa 0
Sample Output
The highest possible quality is 1/3.
题意:每两个字符串相应位置上字母不同的个数作为这两个字符串的距离。
经典最小生成树,这里提供两种做法,kruskal算法和prim算法。
AC代码例如以下:
kruskal算法。!
。!
!。!。。!
#include<iostream> #include<algorithm> #include<cstdio> using namespace std; struct H{ int l,r,d; }w[5000005]; char map[2005][10]; int f[2005]; int find (int a) { return f[a]==a?a : f[a]=find(f[a]); } bool cmp(H a, H b) { return a.d<b.d; } int main() { int n; int i,j,l; int ans; while(cin>>n,n) { int cur=0; for(i=1;i<=n;i++) { f[i]=i; cin>>map[i]; for(j=1;j<=i;j++) { int t=0; for(l=0;l<7;l++) if(map[i][l]!=map[j][l]) t++; w[cur].l=i; w[cur].r=j; w[cur].d=t; //cout<<w[cur].l<<" "<<w[cur].r<<" "<<w[cur].d<<endl; cur++; } } int ans=0; sort(w,w+cur,cmp); for(i=0;i<cur;i++) { int xx,yy; xx=find(w[i].l); yy=find(w[i].r); if(xx!=yy) { ans+=w[i].d; f[xx]=yy; //cout<<ans<<endl; } } printf("The highest possible quality is 1/%d.\n",ans); } return 0; }
prim算法!。!
!
!
!!!!
!。
#include<iostream> #include<algorithm> #include<cstdio> #define inf 100000000 using namespace std; char map[2005][10]; int f[2005]; int w[2005][2005]; int lc[2005],cc[2005]; int minn,minid; int main() { int n; int i,j,l; int ans; while(cin>>n,n) { int cur=0; for(i=1;i<=n;i++) { f[i]=i; cin>>map[i]; for(j=1;j<=i;j++) { int t=0; for(l=0;l<7;l++) if(map[i][l]!=map[j][l]) t++; w[i][j]=t; w[j][i]=t; } } int ans=0; for(i=1;i<=n;i++) { lc[i]=w[1][i]; cc[i]=1; //cout<<lc[i]<<" "<<cc[i]<<endl; } for(i=1;i<n;i++) { for(j=1,minn=inf;j<=n;j++) { if(lc[j]!=0&&lc[j]<minn) {minn=lc[j];minid=j;} } ans+=minn; //cout<<ans<<" "<<minid<<endl; lc[minid]=0; for(j=1;j<=n;j++) { if(lc[j]!=0&&w[minid][j]<lc[j]) { lc[j]=w[minid][j]; cc[j]=minid; } } } printf("The highest possible quality is 1/%d.\n",ans); } return 0; }
以上是关于POJ 1789 Truck History的主要内容,如果未能解决你的问题,请参考以下文章
POJ - 1789(Truck History)最小生成树