Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
kruskal????不行吗???牛们给看看代码;谢谢~~~~#include "stdio.h" #include "iostream" using namespace std; double shortest = 0; char t1[21], t2[21]; typedef struct _node { short x; short y; double distance; }Node; Node graph[300000] = {0}; int root[32768]; int heav[32768]; char tempchar[32768][21]; void makeset(int i) { root[i] = i; heav[i] = 1; } int findset(int i) { if (root[i] != i) root[i] = findset(root[i]); return root[i]; } void unio(int i, int j) { if (heav[i] > heav[j]) { root[j] = i; heav[i] = heav[i] + heav[j]; } else { root[i] = j; heav[j] = heav[i] + heav[j]; } } void kruskal(int i) { int t, k; t = findset(graph[i].x); k = findset(graph[i].y); if (t != k) { shortest = shortest + graph[i].distance; unio(t, k); } } int compare(void const *a, void const *b) { if (((Node *)a)->distance == ((Node *)b)->distance) return 0; return ((Node *)a)->distance > ((Node *)b)->distance?1:-1; } int main() { //freopen("e:\\in.txt", "r", stdin); double totalnum = 0; int N,line; int index = -1; double tempdistance; while(scanf("%lf", &totalnum) != EOF) { memset(graph, 0, sizeof(graph)); shortest = 0; index = -1; scanf("%d", &N); getchar();//eat the '\n' for (int i = 0; i < N; ++i) { gets(tempchar[i]); } scanf("%d", &line); getchar(); for (int i = 0; i < line; ++i) { scanf("%s %s %lf", t1, t2, &tempdistance); getchar(); index++; for (int j = 0; j < N; ++j) { if ((strcmp(t1, tempchar[j])) == 0) { graph[index].x = j; } if ((strcmp(t2, tempchar[j]) == 0)) { graph[index].y = j; } } graph[index].distance = tempdistance; } qsort(graph, (size_t)index, sizeof(Node), compare); for (int i = 0; i < N; ++i) makeset(i); for (int i = 0; i <= index; ++i) kruskal(i); ////////////////////////////////////////////// if (shortest > totalnum) { printf("Not enough cable\n"); } else { printf("Need %.1lf miles of cable\n", shortest); } } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator