Ice_cream’s world III
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1163 Accepted Submission(s): 386
Problem Description
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.
Input
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.
Output
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.
Sample Input
2 1 0 1 10 4 0
Sample Output
10 impossible模板题:prim算法库鲁斯卡尔算法:#include<stdio.h> #include<stdlib.h> #include<string.h> #define inf 10000000 #define ac 1100 int map[ac][ac],cost[ac],v[ac]; int road,country; void prim() { int i,j,k; int next,mincost,outcome=0; memset(v,0,sizeof(v)); for(i=0;i<country;i++) cost[i]=map[0][i]; v[0]=1; for(i=1;i<country;i++) { mincost=inf; for(j=0;j<country;j++)//寻找最短的路 { if(!v[j]&&mincost>cost[j]) { mincost=cost[j]; next=j; } } if(mincost>=inf) { printf("impossible\n\n"); return ; } outcome+=mincost; v[next]=1; for(j=0;j<country;j++)//更新路径 { if(!v[j]&&cost[j]>map[next][j]) cost[j]=map[next][j]; } } printf("%d\n\n",outcome); } int main() { int i,j; int a,b,c; while(scanf("%d%d",&country,&road)!=EOF) { for(i=0;i<country;i++) for(j=0;j<country;j++) { if(i==j) map[i][j]=0; else map[i][j]=inf; } for(i=0;i<road;i++) { scanf("%d%d%d",&a,&b,&c); if(map[a][b]>c) map[a][b]=map[b][a]=c; } prim(); } }
#include<stdio.h> #include<algorithm> using namespace std; #include<math.h> #include<string.h> #define inf 999999999 #define max 10005 #define ac 1005 int city ,road; int set[ac]; struct line { int start; int end; int dist; }num[max]; bool cmp(line a,line b) { return a.dist <b.dist ; } int find(int p) { int t; int child=p; while(p!=set[p]) p=set[p]; while(child!=p) { t=set[child]; set[child]=p; child=t; } return p; } void merge(int x,int y) { int fx=find(x); int fy=find(y); if(fx!=fy) set[fx]=fy; } int main() { int i; while(scanf("%d%d",&city,&road)!=EOF) { for(i=0;i<road;i++) { scanf("%d%d%d",&num[i].start ,&num[i].end ,&num[i].dist ); } for(i=0;i<city;i++) { set[i]=i; } sort(num,num+road,cmp); int outcome=0; for(i=0;i<road;i++) { if(find(num[i].start )!=find(num[i].end ))//判断是否成环 { merge(num[i].start ,num[i].end ); outcome+=num[i].dist ; } } int k=0; for(i=0;i<city;i++)//根的数量 { if(set[i]==i) k++; } if(k>1) printf("impossible\n\n"); else printf("%d\n\n",outcome); } }
原题目: hdoj2122Ice_cream’s world III