专题测试 搜索 B - DZY Loves Chemistry
- 题目
DZY loves chemistry, and he enjoys mixing chemicals.
DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.
Find the maximum possible danger after pouring all the chemicals one by one in optimal order.
InputThe first line contains two space-separated integers n and m .
Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input.
Consider all the chemicals numbered from 1 to n in some order.
OutputPrint a single integer — the maximum possible danger.
ExamplesInput1 0
Output1
Input2 1 1 2
Output2
Input3 2 1 2 2 3
Output4
In the first sample, there's only one way to pour, and the danger won't increase.
In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.
In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).
- 思路
并查集,套样板就行了,答案的形式是pow(2,n),n是全部化学物质的数量减去并查集的集合数,最大化危险度的放法是从每个并查集根节点(祖宗)那个化学物质开始放,再依次放后代。数据有点大可能要用long long存。
果然还是高中培训时期离现在有点久了,连并查集都差点想不起来是啥了,提交时间过了才交,之后还是要加强练习
但是这道题怎么会丢到搜索题里来 - 代码
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> int father[55]; int find(int x) { if(father[x]!=x) father[x] = find(father[x]); return father[x]; } int main() { int n,m,x,y; long long ans; int q; scanf("%d%d",&n,&m); q=n; for(int i=1;i<=n;i++) father[i] = i; for(int i=1;i<=m;i++) { scanf("%d%d",&x,&y); int a=find(x); int b=find(y); father[a] = b; } for(int i = 1; i <= n; i++) { if(father[i] == i) q--; } ans=pow(2,q); printf("%lld\n",ans); return 0; }