codeforces 445 B. DZY Loves Chemistry
http://codeforces.com/contest/445/problem/B
题意:一共有n种化学药品。m对关系,每对关系表示为x,y表示x和y相互反应。初始容器的danger值为1,当向容器中加入一个化学药品A,如果容器中存在化学药品和A反应,那么容器的danger值翻倍。否则不变。问一个最优的放置药品的顺序。
思路:容易发现。如果两个药品相互反应就连一条边。实际上这些药品构成了一个森林。而一个节点只要不是树的根节点,那么它在任何位置,对答案的贡献度都是*2.反过来说。所有的节点,只有根节点是对答案没有贡献的。那实际上,我们只需要dfs一遍,得到树的数目,用n减去树的数目,就是对答案有贡献的点的数目。
要注意开long long 。。。
1/* ***********************************************
2Author :111qqz
3Created Time :2015年12月05日 星期六 17时13分51秒
4File Name :code/cf/problem/445/B.cpp
5************************************************ */
6
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define fst first
20#define sec second
21#define lson l,m,rt<<1
22#define rson m+1,r,rt<<1|1
23#define ms(a,x) memset(a,x,sizeof(a))
24typedef long long LL;
25using namespace std;
26const double eps = 1E-8;
27const int dx4[4]={1,0,0,-1};
28const int dy4[4]={0,-1,1,0};
29const int inf = 0x3f3f3f3f;
30const int N=55;
31bool vis[N];
32int n,m;
33vector<int>edge[N];
34LL ans;
35LL tree_num;
36void dfs( int cur)
37{
38
39 vis[cur] = true;
40 for ( int i = 0 ; i < edge[cur].size(); i++)
41 {
42 int v = edge[cur][i];
43 if (!vis[v])
44 {
45 dfs(v);
46 }
47 }
48}
49int main()
50{
51 #ifndef ONLINE_JUDGE
52 freopen("code/in.txt","r",stdin);
53 #endif
54
55 scanf("%d %d",&n,&m);
56 ms(vis,false);
57 for ( int i = 0 ; i < m ; i++)
58 {
59 int u,v;
60 scanf("%d %d",&u,&v);
61 edge[u].push_back(v);
62 edge[v].push_back(u);
63 }
64 tree_num = 0 ;
65 for ( int i = 1 ; i <= n ; i++)
66 {
67 if (!vis[i])
68 {
69 dfs(i);
70 tree_num++;
71 }
72 }
73 ans = 1;
74 ans = (LL)(1)<<(LL(n-tree_num));
75 cout<<ans<<endl;
76
77 #ifndef ONLINE_JUDGE
78 fclose(stdin);
79 #endif
80 return 0;
81}