UVA 1160 x-plosives
Test Instructions:
Now there are some compounds on hand, each of which is different and consists of two distinct integers , when you have this condition in your hand:
There are at least N (n>2) compounds on the hand and n compounds that contain exactly n different integers (that is, each of the n integers appears 2 times). So the compound is unstable at this time. For example you have a compound (2,3), (3,1) then is unstable, but if you only (2,3), then is stable.
Now give the order of all the compounds to you, and make sure that there is no instability in the compound, and output the number of compounds you need to reject.
Input: Contains multiple sets of instances. Each instance consists of successive pairs of integers (integers belong to [0,10^5]). There is a blank line between the different instances, and no duplicate compounds appear, and a single line of 1 indicates the end of the input for the current instance.
Output: Outputs the number of compounds you need to reject.
Analysis:
Consider each integer as a node, the corresponding compound as the corresponding edge, then a graph is formed.
in the diagram there is a condition that the compound is unstable.
we add a compound that is unstable and necessary if the two elements of the compound already belong to the same connected component.
When two elements of a compound are judged to be in the same connected component, they can be rejected directly.
The input format of input data should be handled with care.
#include <cstdio>
#include <cstring>
using namespace Std;
#define MAXN 500005
int PRE[MAXN];
int Find (int m)
{
int n=m;
while (N!=pre[n])
N=pre[n];
return n;
}
void Merge (int x,int y)
{
int Fx=find (x);
int Fy=find (y);
if (fx<fy)
pre[fy]=fx;//Big Pointing Small
Else
Pre[fx]=fy;
}
void Init ()
{
int i;
for (i=0;i<500005;i++)
Pre[i]=i;
}
int main ()
{
int x, y;
while (scanf ("%d", &x) ==1)
{
if (x==-1)//special case
{
printf ("0\n");
Continue
}
int cnt=0;//Number of compounds that need to be rejected
Init ();
while (X!=-1)
{
scanf ("%d", &y);
if (find (x) = = Find (y))
++cnt;
Else
Merge (x, y);
scanf ("%d", &x);
}
printf ("%d\n", CNT);
}
return 0;
}