Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1074 Accepted Submission(s): 345
2 1 0 1 10 4 0
10 impossible
kruskal:
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; struct node { int s,t,c; }p[1001000]; int cmp(node a,node b) { return a.c < b.c; } int n,m; int per[1100]; void init() { for(int i=0; i < 1010; i++) per[i] = i; } int find(int x) { if( x == per[x] ) return x; return per[x] = find(per[x]); } int join(int x,int y) { int fx = find(x); int fy = find(y); if(fx != fy) { per[fx] = fy; return 1; } return 0; } int main() { int i,j,k; while(scanf("%d%d",&n, &m)!=EOF) { init(); for(i = 0; i < m; i++) { scanf("%d%d%d",&p[i].s ,&p[i].t ,&p[i].c ); } sort( p, p+m, cmp); int cost = 0; for(i = 0; i < m; i++) { if(join(p[i].s,p[i].t)) cost += p[i].c; } int flag = 0; for(i = 0; i < n;i++) { if(per[i] == i) { flag++; if(flag > 1) break; } } if(flag > 1) puts("impossible\n"); else printf("%d\n\n",cost); } return 0; }
prim:
#include<cstdio> #include<cstring> #include<cmath> #define mem(a, b) memset(a, (b), sizeof(a)) #define Wi(a) while(a--) #define Si(a,b) scanf("%d%d", &a,&b) #define Pi(a) printf("%d\n\n", (a)) #define INF 0x3f3f3f int map[1010][1010]; int n,m; int vis[1010]; int d[1010]; void prim() { mem(vis, 0); int i, j, k; int ans = 0, minn; for(i = 0; i < n; i++) d[i] = map[1][i]; vis[1] = 1; for(i = 1; i < n; i++) { k = 1; minn = INF; for(j = 0; j < n; j++) { if(!vis[j] && d[j] < minn) { minn = d[j]; k = j; } } if(minn == INF)//无法联通所有 { puts("impossible\n");return ; } vis[k] = 1; ans += minn; for(j = 0; j < n; j++) { if(!vis[j] && d[j] > map[j][k]) d[j] = map[j][k]; } } Pi(ans); } int main(){ while(Si(n,m)==2) { int i,j,k; for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { map[i][j] = INF; } map[i][i] = 0; } int a, b, c; Wi(m) { scanf("%d%d%d", &a, &b, &c); if(map[a][b] > c) map[a][b] = map[b][a] = c; } prim(); } return 0; }