标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 14935 Accepted Submission(s): 5691
Source Code:
#include <iostream> #include <algorithm> using namespace std; struct road{ int start; int end; int cost; }; int maze[110][110]; road RoadsArr[100000]; int Root[110]; bool cmp(road a,road b){ return a.cost<=b.cost; } void initRoot(int length){ for(int i=1;i<=length;++i) Root[i]=-1; } int findRoot(int x){ if(Root[x]==-1) return x; else{ int tmp=findRoot(Root[x]); Root[x]=tmp; return tmp; } } int Kruskal(int length){ int answer=0; for(int i=0;i<length;++i){ int Root_a=findRoot(RoadsArr[i].start); int Root_b=findRoot(RoadsArr[i].end); if(Root_a!=Root_b){ Root[Root_a]=Root_b; answer+=RoadsArr[i].cost; } } return answer; } int main(){ int N,Q; while(cin>>N){ initRoot(N); int index=0; for(int i=1;i<=N;++i){ for(int j=1;j<=N;++j){ cin>>maze[i][j]; if(i!=j){ RoadsArr[index].start=i; RoadsArr[index].end=j; RoadsArr[index].cost=maze[i][j]; ++index; } } } sort(RoadsArr,RoadsArr+index,cmp); cin>>Q; int city_a,city_b; for(int i=0;i<Q;++i){ cin>>city_a>>city_b; int Root_a=findRoot(city_a); int Root_b=findRoot(city_b); if(Root_a!=Root_b) Root[Root_a]=Root_b; } int answer=Kruskal(index); cout<<answer<<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/Murcielago/p/4243527.html