蓝桥杯 城市建设
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn = 1e5 + 10; 4 const int INF = 1e9; 5 struct Edge 6 { 7 int u, v; 8 int dis; 9 }edge[maxn * 100]; 10 int n, m; 11 int cnt; 12 int port[maxn]; 13 vector<int> vec; 14 int fa[maxn]; 15 int ans; 16 17 bool cmp(Edge a, Edge b) 18 { 19 return a.dis < b.dis; 20 } 21 22 23 void init() 24 { 25 for(int i = 0; i <= n; i++) 26 fa[i] = i; 27 } 28 29 30 int findfa(int x) 31 { 32 if(fa[x] == x) 33 return x; 34 else 35 return fa[x] = findfa(fa[x]); 36 } 37 38 int Kruskal(int edgenum, int vernum) 39 { 40 int num = 0; 41 int res = 0; 42 for(int i = 0; i < edgenum; i++) 43 { 44 //if(num == n - 1) break; 45 int x = edge[i].u; 46 int y = edge[i].v; 47 int d = edge[i].dis; 48 49 int fx = findfa(x); 50 int fy = findfa(y); 51 52 if(fx != fy) 53 { 54 fa[fy] = fx; 55 res += d; 56 //ans += d; 57 num++; 58 59 } 60 else if(d < 0) 61 res += d; 62 //ans += d; 63 } 64 if(num == vernum - 1) return res; 65 else return -1; 66 //return num; 67 } 68 69 70 int main() 71 { 72 int a, b, c; 73 74 cin >> n >> m; 75 for(int i = 0; i < m; i++) 76 { 77 scanf("%d%d%d", &a, &b, &c); 78 edge[i].u = a; 79 edge[i].v = b; 80 edge[i].dis = c; 81 } 82 cnt = m; 83 84 for(int i = 1; i <= n; i++) 85 { 86 scanf("%d", &port[i]); 87 if(port[i] < 0) continue; 88 edge[cnt].u = 0; 89 edge[cnt].v = i; 90 edge[cnt].dis = port[i]; 91 cnt++; 92 } 93 sort(edge, edge + m, cmp); 94 init(); 95 ans = Kruskal(m, n); 96 //int flag = Kruskal(m, n); 97 sort(edge, edge + cnt, cmp); 98 init(); 99 //int t = flag; 100 int mid = ans; 101 ans = Kruskal(cnt, n + 1); 102 //flag = Kruskal(cnt, n + 1); 103 if(mid == -1) 104 { 105 cout << ans << endl; 106 } 107 else 108 { 109 ans = min(ans, mid); 110 cout << ans << endl; 111 } 112 113 return 0; 114 }
posted on 2019-05-29 23:10 stagelovepig 阅读(173) 评论(0) 编辑 收藏 举报