前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【POJ 1789】Truck History(最小生成树)

【POJ 1789】Truck History(最小生成树)

作者头像
饶文津
发布2020-06-02 15:49:59
3860
发布2020-06-02 15:49:59
举报
文章被收录于专栏:饶文津的专栏饶文津的专栏

题意:距离定义为两个字符串的不同字符的位置个数。然后求出最小生成树。

代码语言:javascript
复制
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=2001;
const int M=4000001;
char code[N][10];
int f[N];//并查集
struct edge{
    int u,v,w;
}e[M];
int n,tot;
void add(int u,int v,int w){
    e[tot].u=u;e[tot].v=v;e[tot++].w=w;
}
bool cmp(edge a,edge b){
    return a.w<b.w;
}
int find(int x){
    if(f[x]==-1)return x;
    return f[x]=find(f[x]);
}
int Kruskal(){
    memset(f,-1,sizeof f);
    sort(e,e+tot,cmp);
    int cnt=0,ans=0;
    for(int i=0;i<tot;i++){
        int u=e[i].u,v=e[i].v,w=e[i].w;
        int fu=find(u),fv=find(v);
        if(fu!=fv){
            ans+=w;
            f[fu]=fv;
            cnt++;
        }
        if(cnt==n-1)break;
    }
    return ans;
}
void solve(){
    for(int i=1;i<=n;i++)
    for(int j=i+1;j<=n;j++)
    {
        int dis=0;
        for(int k=0;k<7;k++)
            if(code[i][k]!=code[j][k])dis++;
        add(i,j,dis);
    }
}
int main(){
    while(scanf("%d ",&n),n){
        tot=0;
        for(int i = 1; i <= n; i++)
            gets(code[i]);
        solve();
        printf("The highest possible quality is 1/%d.\n", Kruskal());
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-08-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档