专题四 · 1006

来源:互联网 发布:苏州激光切割编程招聘 编辑:程序博客网 时间:2024/05/29 03:15

代码及解释

#include <iostream>#include <algorithm>// 天真的把上一道题稍微改了改,// 以为能过,结果 WA 了 (》:o 」∠)_// 然后又老老实实的重新写了using std::cin;using std::cout;using std::endl;char set[1000];int n,k;struct edge {  char s,e;  int w;} e[1000];inline bool cmp(edge a,edge b) {  return a.w<b.w;}char find_f(char x) {  return set[x] == x ? x : set[x] = find_f(set[x]);}int Kruskal() {  int sum = 0;  for(int i = 0; i < k; ++i) {    char x = find_f(e[i].s);    char y=find_f(e[i].e);    if(x != y) {      set[x] = y;      sum += e[i].w;    }  }  return sum;}int main() {  while(cin >> n && n) {    char rs, re;    int m, rw;    k=0;    n--;    while(n--) {      cin >> rs >> m;      while(m--) {        cin >> re >> rw;        e[k].s = rs;        e[k].e = re;        e[k].w = rw;        k++;      }    }    for(char i = 'A'; i <= 'Z'; ++i)      set[i] = i;    std::sort(e, e + k, cmp);    cout << Kruskal() << endl;  }  return 0;}
0 0
原创粉丝点击