zoukankan      html  css  js  c++  java
  • hdu 3172 Virtual Friends

    原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=3172 
    并查集的运用。。。

     1 #include<algorithm>
     2 #include<iostream>
     3 #include<cstdlib>
     4 #include<cstdio>
     5 #include<map>
     6 using std::map;
     7 using std::string;
     8 const int Max_N = 100010;
     9 struct UnionFind {
    10     map<string, int> rec;
    11     int num[Max_N], par[Max_N];
    12     void init() {
    13         for (int i = 1; i < Max_N; i++) {
    14             par[i] = i;
    15             num[i] = 1;
    16         }
    17         rec.clear();
    18     }
    19     inline int find(int x) {
    20         while (x != par[x]) {
    21             x = par[x] = par[par[x]];
    22         }
    23         return x;
    24     }
    25     inline void unite(int x, int y) {
    26         x = find(x), y = find(y);
    27         if (x != y){
    28             par[x] = y;
    29             num[y] += num[x];
    30             printf("%d
    ", num[y]);
    31         } else {
    32             printf("%d
    ", num[y]);
    33         }
    34     }
    35     inline void gogo() {
    36         int n, cnt = 1;
    37         char s1[100], s2[100];
    38         scanf("%d", &n);
    39         while (n--) {
    40             scanf("%s %s", s1, s2);
    41             if (!rec[s1]) rec[s1] = cnt++;
    42             if (!rec[s2]) rec[s2] = cnt++;
    43             unite(rec[s1], rec[s2]);
    44         }
    45     }
    46 }ans;
    47 int main() {
    48 #ifdef LOCAL
    49     freopen("in.txt", "r", stdin);
    50     freopen("out.txt", "w+", stdout);
    51 #endif
    52     int t;
    53     while (~scanf("%d", &t)) {
    54         while (t--) ans.init(), ans.gogo();
    55     }
    56     return 0;
    57 }
    View Code
    By: GadyPu 博客地址:http://www.cnblogs.com/GadyPu/ 转载请说明
  • 相关阅读:
    2.17-2.23第一周总结
    10号总结
    9日总结
    8号总结
    7号寒假总结
    6号
    读后感《程序员的修炼之道:从小工到专家》1
    java第二次动手动脑
    回文判断
    二进制的原码,反码以及补码介绍
  • 原文地址:https://www.cnblogs.com/GadyPu/p/4528871.html
Copyright © 2011-2022 走看看