zoukankan      html  css  js  c++  java
  • CodeForces 445B DZY Loves Chemistry (并查集)

    题意:

      有N种药剂编号 1 ~ N,然后有M种反应关系,这里有一个试管,开始时危险系数为 1,每当放入的药剂和瓶子里面的药剂发生反应时危险系数会乘以2,否则就不变,给出N个药剂和M种反应关系,求最大的危险系数。

    思路:

      我们假设 1 ~ N   有 M 种反应关系 ,若果有反应关系的我们可以把他们看成是一个集合  ,假设这M种反应构成了 T个集合,那么把这T个集合中的元素依次放入试管,有几个不发生反应呢?当然是T个了,把每个集合看成是一课树,根节点和其子节点反应,这个子节点又和它的子节点发生反应、想一想是一个链状的结构、、、假设每个集合放入时先放根节点(第一个节点),那么每个根节点是不是都不和当前试管中的药剂发生反应呢,因为根节点只和它的子节点发生发应,而他的子节点尚未放入、、所以把这些药剂全部放入,最少只需要 T 个不发生发应,我们只需要用并查集计算下一共有几个集合然后用总的药剂数量减去这几个不发生发应的,就可以计算出来我们要的值了。注意的是题目给的是1 ~ 50 那么假设全部发生反应  2的50次方需要用 long long 存放,第一次WA在了这里!!!!。。。

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <cstdlib>
     5 #include <cmath>
     6 #include <cctype>
     7 #include <algorithm>
     8 using namespace std;
     9 const int MAXN = 1e2 + 3;
    10 int pre[MAXN];
    11 
    12 int Find(int x)
    13 {
    14     int r = x;
    15     while(pre[r] != r)
    16     {
    17         r = pre[r];
    18     }
    19     int i = x,j;
    20     while(pre[i] != r)
    21     {
    22         j = i;
    23         i = pre[i];
    24         pre[j] = r;
    25 
    26     }
    27     return r;
    28 }
    29 
    30 void Mix(int a,int b)
    31 {
    32     int x = Find(a);
    33     int y = Find(b);
    34     if(x > y)
    35     {
    36         pre[x] = y;
    37     }
    38     if(x < y)
    39     {
    40         pre[y] = x;
    41     }
    42 }
    43 int main()
    44 {
    45     //freopen("in.cpp","r",stdin);
    46     //fropen("out.txt","w",stdout);
    47     long long M,N;
    48     scanf("%lld%lld",&N,&M);
    49     for(int i = 1; i <= N; i++)
    50         pre[i] = i;
    51     while(M--)
    52     {
    53         int a,b;
    54         scanf("%d%d",&a,&b);
    55         Mix(a,b);
    56     }
    57     long long root = 0;
    58     for(int i = 1; i <= N; i++)   //统计有多少个集合
    59         if(pre[i] == i)
    60             root++;
    61     long long ans = 1;
    62     printf("%lld
    ",(ans<<(N -root)));   //N - root便是发生发应的次数
    63     return 0;
    64 }
  • 相关阅读:
    第2季:从官方例程深度学习海思SDK及API
    H.264帧结构详解
    Linux内核链表
    在Sqlite中通过Replace来实现插入和更新
    mysql 里随机生成时间
    搭建Cordova + Ionic + WebStorm环境开发Web App应用
    Angular Local Storage 使用方法
    angularJS中controller与directive双向通信
    ui-router传递参数
    Sequelize 和 MySQL 对照
  • 原文地址:https://www.cnblogs.com/Ash-ly/p/5397647.html
Copyright © 2011-2022 走看看