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 <iostream> #include <algorithm> using namespace std; int m,nEdge; int parent[200]={0},rank[200]={0}; struct BCSet { void makeSet(int i) { parent[i]=i; rank[i]=1; } int findSet(int i) { if(parent[i]!=i) { parent[i] = findSet(parent[i]); } return parent[i]; } void unionSet(int i, int j) { if(rank[i] > rank[j]) { parent[j] = i; } else if(rank[i] < rank[j]) { parent[i] = j; } else { rank[j]++; parent[i] = j; } } }; struct Edge { int u,v,d; bool flag; Edge(){;} Edge(int uu, int vv, int dd) { u = uu; v = vv; d = dd; flag = true; } bool operator < (const Edge e) { return d<e.d; } }edge[200*200]; int main() { int i,j,q,u,v,len; BCSet set; while(scanf("%d",&m) != EOF) { for(i=0; i<m; i++) { set.makeSet(i); } nEdge=0; len=0; for(i=0; i<m; i++) { for(j=0; j<m; j++) { if(j>i) { edge[nEdge].u=i; edge[nEdge].v=j; edge[nEdge].flag=true; scanf("%d",&edge[nEdge++].d); } else { scanf("%*d"); } } } sort(edge,edge+nEdge); scanf("%d",&q); for(i=0; i<q; i++) { scanf("%d%d",&u,&v); for(j=0; j<nEdge; j++) { if(edge[j].u==u-1 && edge[j].v==v-1) { edge[j].flag=false; set.unionSet(set.findSet(edge[j].u),set.findSet(edge[j].v)); break; } } } for(i=0; i<nEdge; i++) { if(edge[i].flag && set.findSet(edge[i].u)!=set.findSet(edge[i].v)) { set.unionSet(set.findSet(edge[i].u),set.findSet(edge[i].v)); len += edge[i].d; } } printf("%d\n",len); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator