The minimum spanning tree modeling + POJ - 1789Truck History

History Truck
the Description:
given N strings, each string are inherited from another string (except ancestor string), it takes a string into another string for each of them are not the same character number. Q. seek minimum cost

The relationship between the point and the point is the relationship between the string and the string, not every one is the same number of characters right side, eventually each point must have a parent node (connectivity tree), not multiple inheritance (acyclic).

Here Insert Picture Description

Note:
Do not enter the stream, and the string with c ++ cin, too slow so TLE .

#include<stdio.h>
#include<iostream>
#include<cmath>
#include<math.h>
#include<string>
#include<string.h>
#include<algorithm>
#define ll long long
using namespace std;
const int maxn=2005;  //数组要开够
int n,m,fa[maxn];
char dots[2005][10];
struct Edge{
    int u,v,cost;
}t[maxn*maxn];

int get_cost(int x,int y){
    int sum=0;
    for(int i=0;i<7;i++){
        if(dots[x][i]!=dots[y][i]) sum++;
    }
    return sum;
}

bool cmp(Edge a,Edge b){
    return a.cost<b.cost;
}

int find(int x){
    return (x==fa[x])?x:fa[x]=find(fa[x]);
}
void merge(int x,int y){
    fa[find(x)]=find(y);
}

int main(){
    while(scanf("%d",&n)&& n){
        m = n*(n-1)/2;
        for(int i=1;i<=n;i++) scanf("%s",dots[i]);
        int cnt=1;
        for(int i=1;i<n;i++){
            for(int j=i+1;j<=n;j++){
                t[cnt].u=i;t[cnt].v=j;t[cnt].cost=get_cost(i,j);
                cnt++;
            }
        }
        for(int i=1;i<=n;i++) fa[i]=i;
        sort(t+1,t+m+1,cmp);
        int ans=0;
        for(int i=1;i<=m;i++){
            int u=t[i].u,v=t[i].v;
            if(find(u)!=find(v)){
                ans+=t[i].cost;
                merge(u,v);
            }
        }
        printf("The highest possible quality is 1/%d.\n",ans);
    }
    return 0;
}
Published 44 original articles · won praise 0 · Views 842

Guess you like

Origin blog.csdn.net/qq_44846324/article/details/104564946