C - small Xin castle

Description

Once there was a king, he called the Little Xin. One day, he wanted to build a castle, so designers gave him a lot of simple design drawings, mainly communicated drawing room. Xin little hope any of the two rooms has one and only one path can be connected. Small Xin now the design to you, let you help determine the design meets his ideas. For example the following example, the first one is eligible, but the second is not met, since there are two paths (5-3-4 and 5-6-4) from 5-4.
Here Insert Picture DescriptionHere Insert Picture Description
Input

Plural sets of inputs, each line contains a first integer m (m <100000), the next m lines of two integers representing the number of two rooms a channel connection. No room is at least 1 and not more than 100,000.
Output

Each data output line, if the castle in line with the idea of small Xin, then output "Yes", otherwise a "No".
Sample

Input

5
2 5
2 3
1 3
3 6
4 6
6
1 2
1 3
3 4
3 5
5 6
6 4
Output

Yes
No
idea: all points are connected together, each group will enter a judgment before watching this group is not previously connected in disjoint-set, the situation if the output is NO, NO is also a group of these points FIG communication can not be connected, so that with a VIS [] recording points, to see whether the entered points, and determines whether a root which points.

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int vis[100010];
int f[100010];
void init()
{
    for(int i=1;i<100010;i++)
        f[i] = i;
}
int getf(int v)
{
    if(f[v] == v)
        return v;
    else
    {
        f[v] = getf(f[v]);
        return f[v];
    }
}
void Merge(int u,int v)
{
    int t1,t2;
    t1 = getf(u);
    t2 = getf(v);
    if(t1 != t2)
    {
        f[t2] = t1;
    }
}
int main()
{
    int t;
    int u,v;
    while(~scanf("%d",&t))
    {
        int sum = 0;
        init();
        memset(vis,0,sizeof(vis));
        int flag = 0;
        for(int i=0;i<t;i++)
        {
            scanf("%d %d",&u,&v);
            vis[u] = vis[v] = 1;//标记这个点是否输入过
            if(f[u] == f[v])//防止成环
            {
                flag = 1;
            }
            else
                Merge(u,v);
        }
        for(int i=1;i<=100000;i++)
        {
            if(f[i] == i&&vis[i])
                sum++;
        }
        if(sum>1)
            flag = 1;
        if(flag == 0)
            printf("Yes\n");
        else
            printf("No\n");
    }

    return 0;

}

Published 177 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/Fusheng_Yizhao/article/details/104914763