poj1258 kruskal算法+并查集 只要47MS我也是醉了

来源:互联网 发布:三菱plc fx仿真软件 编辑:程序博客网 时间:2024/06/11 19:43
//poj1258  kruskal算法+并查集 为什么只要47MS? #include <iostream>#include <algorithm>#define inf 100005using namespace std;int max1;int father[105];int rank[105];struct edge{int st;int ed;int w;}e[10005];int top = 0;void addEdge(int x, int y, int z){e[top].st = x;e[top].ed = y;e[top].w = z;top++;}void makeset(int n){for(int i = 0; i < n; i++){father[i] = i;rank[i] = 0;}}int find(int x){if(x != father[x])father[x] = find(father[x]);return father[x];}bool Union(int x, int y){int px = find(x);int py = find(y);if(px != py){if(rank[px] > rank[py])father[py] = px;else{if(rank[px] == rank[py])rank[py]++;father[px] = py;}return true;}return false;}int cmp(const void* a, const void* b){return ((edge*)a)->w - ((edge*)b)->w;}int kruskal(int n){//排序qsort(e, top, sizeof(e[0]), cmp); for(int i = 0; i < top; i++) { if(Union(e[i].st, e[i].ed)) {max1 += e[i].w;   } }return max1;}int main(){int n; cin>>n;while(n && !cin.eof()){top = 0;for(int i = 0; i < n; i++){for(int j = 0; j < n; j++){int w;cin>>w;addEdge(i, j, w);}}makeset(n); max1 = 0; cout<<kruskal(n)<<endl; cin>>n;}return 0;}

0 0
原创粉丝点击