A secret service developed a new kind of explosivethat attain its volatile property only when a specific association of productsoccurs. Each product is a mix of two different simple compounds, to which wecall abinding pair. If N>2, then mixing N different binding pairscontaining N simple compounds creates a powerful explosive.For example,the binding pairs A+B, B+C, A+C (three pairs, three compounds) result in anexplosive, while A+B, B+C, A+D (three pairs, four compounds) does not.
You are not a secret agent but only a guy in adelivery agency with one dangerous problem: receive binding pairs in sequentialorder and place them in a cargo ship. However, you must avoid placing in thesame room an explosive association. So, after placing a set of pairs, if youreceive one pair that might produce an explosion with some of the pairs alreadyin stock, you must refuse it, otherwise, you must accept it.
An example. Let’s assume you receive the followingsequence: A+B, G+B, D+F, A+E, E+G, F+H. You would accept the first four pairsbut then refuse E+G since it would be possible to make the following explosivewith the previous pairs: A+B, G+B, A+E, E+G (4 pairs with 4 simple compounds).Finally, you would accept the last pair, F+H.
Compute the number of refusals given a sequence ofbinding pairs.
Input
The input will contain several test cases, each of themas described below. Consecutive test cases are separated by a single blankline.
Instead of letters we will use integers torepresent compounds. The input contains several lines. Each line (except thelast) consists of two integers (each integer lies between 0 and 105)separated by a single space, representing a binding pair. The input ends in aline with the number –1. You may assume that no repeated binding pairs appearsin the input.
Output
For each test case, a single line with the numberof refusals.
Sample Input
1 2
3 4
3 5
3 1
2 3
4 1
2 6
6 5
-1
Sample Output
3
题目简介:如果A+B,A+C,B+C同时存在就会爆炸。A+B等价与B+A。计算最多不会爆炸的数目。
方法:一个裸的并查集。
#include<stdio.h> int p[100010]; int find(int x) { if(p[x]!=x) { return p[x] = find(p[x]); } return x; }; int merge(int x, int y, int z) { x = find(x); y = find(y); if(x==y) { z++; } else { p[x] = y; } return z; } int main() { int a ,b ,i; int num; while(scanf("%d",&a)!=EOF) { for(i = 0;i<100010;i++) { p[i] = i; } num = 0; while(a!=-1) { scanf("%d",&b); num = merge(a,b,num); scanf("%d",&a); } printf("%d\n",num); } return 0; }