您的位置:首页 > 其它

HDOJ 2122 Ice_cream’s world III【Prime】&【Kruskal】

2015-11-04 21:42 387 查看

Ice_cream’s world III

Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 1384 Accepted Submission(s): 465

[align=left]Problem Description[/align]
ice_cream’s world becomes stronger and stronger; every road is built as undirected. The queen enjoys traveling around her world; the queen’s requirement is like II problem, beautifies the roads, by which there are some ways from every
city to the capital. The project’s cost should be as less as better.

[align=left]Input[/align]
Every case have two integers N and M (N<=1000, M<=10000) meaning N cities and M roads, the cities numbered 0…N-1, following N lines, each line contain three integers S, T and C, meaning S connected with T have a road will cost C.

[align=left]Output[/align]
If Wiskey can’t satisfy the queen’s requirement, you must be output “impossible”, otherwise, print the minimum cost in this project. After every case print one blank.

[align=left]Sample Input[/align]

2 1
0 1 10

4 0


[align=left]Sample Output[/align]

10

impossible


题目链接:HDOJ 2122 Ice_cream’s world III【Prime】&【Kruskal】

最小生成树 Kruskal Prime 模板

已AC代码已:(Prime)

#include<cstdio>
#include<cstring>
#define INF 0x3f3f3f
#define M 1010
int map[M][M],vis[M],cost[M];
int n,m;

void Prime()
{
int i,j,pos,min,sum=0;
for(i=0;i<n;++i)//将map的第一行存入cost
{
cost[i]=map[0][i];
vis[i]=0;//标记
}
vis[0]=1;
for(i=1;i<n;++i)
{
min=INF;pos=1;
for(j=0;j<n;++j)//找出cost最小值
{
if(!vis[j] && min>cost[j])
{
min=cost[j];
pos=j;
}
}

if(min==INF)//找不到路
{
printf("impossible\n\n");
return ;
}
vis[pos]=1;//标记已找的
sum+=min;//求和

for(j=0;j<n;++j)//更新 cost
if(!vis[j] && cost[j]>map[pos][j])
cost[j]=map[pos][j];
}
printf("%d\n\n",sum);
return ;
}
int main()
{
int i,j,a,b,c;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(map,INF,sizeof(map));

while(m--)
{
scanf("%d%d%d",&a,&b,&c);
if(map[a][b]>c)//取较小的值
map[a][b]=map[b][a]=c;
}

Prime();
}
return 0;
}
已AC代码二:(Kruskal)

#include<cstdio>
#include<cstring>
#include<algorithm>
#define M 1100
using namespace std;
struct NODE{
int from,to,val;
}s[M*10];
int per[M];
int n,m;
bool cmp(NODE a,NODE b)
{
return a.val<b.val;
}
void into()//初始化
{
for(int i=0;i<=n;++i)
per[i]=i;
}
int find(int x)//根节点
{
return x==per[x]?x:per[x]=find(per[x]);
}
int join(int a,int b)//加边
{
int fa=find(a);
int fb=find(b);
if(fa!=fb)
{
per[fa]=fb;
return 1;
}
else
return 0;
}
int main()
{
int k,i,a,b,c;
while(scanf("%d%d",&n,&m)!=EOF)
{
into();
for(k=0;k<m;++k)
{
scanf("%d%d%d",&a,&b,&c);
s[k].from=a;
s[k].to=b;
s[k].val=c;
}
sort(s,s+k,cmp);
int sum=0;
for(i=0;i<k;++i)
{
if(join(s[i].from,s[i].to))
{
sum+=s[i].val;
}
}
int temp=0;
for(i=0;i<n;++i)
{
if(per[i]==i)
temp++;
if(temp==2)
break;
}
if(temp==2)
printf("impossible\n\n");
else
printf("%d\n\n",sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: