【存在已经建好的道路】
答案的思路是已经建好的道路,权值设定为0
我的做法是分成两个队列,先用已建好的道路构造生成树,再处理需要建造的
分阶段完成规划
#include<iostream> #include<vector> #include<algorithm> using namespace std; struct Edge{ int a,b; int cost; int built; }; bool sortByCost(Edge x,Edge y){ return x.cost<y.cost; } int getRoot(int nodes[],int i){ while(nodes[i]!=i){ i = nodes[i]; } return i; } int main(){ int n; while(cin>>n){ int len = n*(n-1)/2; int nodes[100]; vector<Edge> edges; vector<Edge> existEdges; for(int i=0;i<len;i++){ Edge e; cin>>e.a>>e.b>>e.cost>>e.built; nodes[e.a] = e.a; nodes[e.b] = e.b; if(e.built){ existEdges.push_back(e); } else { edges.push_back(e); } } sort(edges.begin(),edges.begin()+edges.size(),sortByCost); sort(existEdges.begin(),existEdges.begin()+existEdges.size(),sortByCost); vector<Edge>::iterator it1 = existEdges.begin(); while(it1!=existEdges.end()){ int root_a = getRoot(nodes,it1->a); int root_b = getRoot(nodes,it1->b); nodes[root_a] = root_b; it1++; } int total = 0; vector<Edge>::iterator it2 = edges.begin(); while(it2!=edges.end()){ int root_a = getRoot(nodes,it2->a); int root_b = getRoot(nodes,it2->b); if(root_a!=root_b){ nodes[root_a] = root_b; total += it2->cost; } it2++; } cout<<total<<endl; } return 0; }