POJ1789(最小生成树,kruskal算法)

编程入门 行业动态 更新时间:2024-10-10 12:25:01

 由于和结点联系非常密切,所以容易想到使用kruskal算法

题意:编写程序输出最高质量的火车推导计划。火车推倒计划质量的求解公式中的分子为1,分母为t0,td的距离总和。

t0,td的距离就是两个输入字符串的字母不同位置的个数。想要推导计划的质量最高就是使分母最小。即t0,td的距离总和最小。

实质上是以任意两个字符串为结点,以字符串字母不同位置的个数为两节点之间边的权值,求解最小生成树。因此输入和结点联系密切,使用kruskal算法求解比较方便。

下面是AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=2005;
char str[maxn][7];
int pre[maxn];
struct truck
{int to;int from;int weight;
} pp[maxn*(maxn>>1)];
int n,qq,ans;
void init()
{ans=0;qq=0;for(int i=0; i<=n; i++)pre[i]=i;
}
bool cmp(truck a,truck b)
{return a.weight<b.weight;
}
int finds(int x)
{if(x==pre[x])return pre[x];pre[x]=finds(pre[x]);return pre[x];
}
void make_tree()
{for(int i=0; i<n; i++)for(int j=n-1; j>=i; j--){int sum=0;for(int x=0; x<7; x++)if(str[i][x]!=str[j][x])sum++;pp[qq].from=i;pp[qq].to=j;pp[qq].weight=sum;++qq;}
}
void kruskal()
{sort(pp,pp+qq,cmp);int to,from;for(int i=0; i<qq; i++){to=finds(pp[i].to);from=finds(pp[i].from);if(to==from);else if(to!=from){pre[to]=from;ans+=pp[i].weight;}}
}
int main()
{while(~scanf("%d",&n)&&n){for(int i=0; i<n; i++)scanf("%s",str[i]);init();make_tree();kruskal();printf("The highest possible quality is 1/%d.\n",ans);}return 0;
}

 

更多推荐

算法,最小,kruskal

本文发布于:2023-06-02 12:05:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/457433.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   最小   kruskal

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!