继续畅通工程

来源:互联网 发布:js拉链 编辑:程序博客网 时间:2024/05/15 21:49

题目网址:继续畅通工程

题目分析:这个比之前的还是畅通工程相比多了一个就是有的路已经修好了,无需在花销,所以我们比之前的做法只是多判断一点,如果已经修过了,那么我们就把这条路的花销修改为0,其他不变。

#include<iostream>#include<algorithm>using namespace std;int parent[102];int findroot(int x){if (parent[x] != x)parent[x] = findroot(parent[x]);return parent[x];}struct edge{int a, b;int cost;bool operator < (const edge&a)const{return cost < a.cost;}}e[6000];int main(){int n;while (cin >> n&&n){for (int i = 1; i <= n; i++){parent[i] = i;}for (int i = 0; i < (n - 1)*n / 2; i++){int state;cin >> e[i].a >> e[i].b >> e[i].cost >> state;if (state == 1)//若是已经修好了,那么直接将cost修改为0e[i].cost = 0;}sort(e, e + (n - 1)*n / 2);int ans = 0;for (int i = 0; i < (n - 1)*n / 2; i++){int a = findroot(e[i].a);int b = findroot(e[i].b);if (a != b){parent[a] = b;ans += e[i].cost;}}cout << ans << endl;}return 0;}

原创粉丝点击