zoukankan      html  css  js  c++  java
  • 1234: ZJTZYRC筛offer(并查集 )

    链接:http://xcacm.hfut.edu.cn/problem.php?id=1234

    以后关于字符的输入都用cin吧,换成scanf居然wa了

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <algorithm>
     5 #include <map>
     6 #include <string>
     7 #include <set>
     8 #define Max 10005
     9 using namespace std;
    10 int pre[Max],Rank[Max];
    11 int sum;
    12 void init()
    13 {
    14     for(int i=0;i<Max;i++)
    15         pre[i]=i;
    16     return;
    17 }
    18 int find(int x)
    19 {
    20     if(pre[x]==x)
    21         return x;
    22     return pre[x]=find(pre[x]);
    23 }
    24 int unite(int a,int b)
    25 {
    26     int x=find(a);
    27     int y=find(b);
    28     if(Rank[x]==Rank[y])
    29         return 0;
    30     sum--;
    31     if(Rank[x]<Rank[y])
    32         pre[y]=x;
    33     else
    34         pre[x]=y;
    35     return 0;
    36 }
    37 int main()
    38 {
    39     int n,m;
    40     char ch;
    41     string s,a,b;
    42     map<string,int> u;
    43     //freopen("in.txt","r",stdin);
    44     //freopen("out.txt","w",stdout);
    45     while(scanf("%d",&n)!=EOF)
    46     {
    47         sum=n;
    48         u.clear();
    49         init();
    50         for(int i=0;i<n;i++)
    51         {
    52             cin>>s;
    53             u[s]=i+1;
    54             Rank[i+1]=i+1;
    55         }
    56         cin>>m;
    57         for(int i=0;i<m;i++)
    58         {
    59             cin>>ch;
    60             if(ch=='a')
    61             {
    62                 cin>>a>>b;
    63                 unite(u[a],u[b]);
    64             }
    65             else if (ch=='q')
    66             {
    67                 cin>>a;
    68                 int r=find(u[a]);
    69                 printf("%d
    ",Rank[r]);
    70             }
    71             else if (ch=='t')
    72                 printf("%d
    ",sum);
    73         }    
    74     }    
    75     return 0;
    76 }
  • 相关阅读:
    tree-cli 自动生成项目目录结构
    按需导入vant-ui
    全局导入vant-ui
    mook使用流程
    axios使用流程
    Vuex使用流程
    vue-router使用流程
    img的complete和onload
    react-redux 如何在子组件里访问store对象
    ES6中的Export/import操作的是引用
  • 原文地址:https://www.cnblogs.com/a1225234/p/5469049.html
Copyright © 2011-2022 走看看