(并查集) bzoj 1161

【bzoj1116】[POI2008]CLO

Description

Byteotia城市有n个 towns m条双向roads. 每条 road 连接 两个不同的 towns ,没有重复的road. 你要把其中一些road变成单向边使得:每个town都有且只有一个入度

Input

第一行输入n m.1 <= n<= 100000,1 <= m <= 200000 下面M行用于描述M条边.

Output

TAK或者NIE 常做POI的同学,应该知道这两个单词的了…

Sample Input

4 5
1 2
2 3
1 3
3 4
1 4

 

Sample Output

TAK

上图给出了一种连接方式.

题解

这题令我突然想到了scoi游戏
首先我们可以推出一个性质,当且仅当某一个连通块中没有环存在输出NIE
于是我们可以用并查集把这题水过。。
给每个连通块的根一个标记
合并俩个连通块时只要任意一个连通块带有标记新的连通块就带有标记
如果一条边的俩个点已经在同一个连通块内了,直接将根打上标记即可
然后最后扫一遍,如果哪个连通块没有标记的话输出NIE
否则最后输出TAK
 
 
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<set>
using namespace std;
int n,m,fa[100005],mark[100005];
int find(int x)
{
    if(x!=fa[x])
        fa[x]=find(fa[x]);
    return fa[x];
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        fa[i]=i;
    for(int i=1;i<=m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        int fx,fy;
        fx=find(x),fy=find(y);
        if(fx!=fy)
        {
            fa[fx]=fy;
            mark[fy]=mark[fy]|mark[fx];
        }
        else
            mark[fy]=1;
    }
    for(int i=1;i<=n;i++)
    {
        if(!mark[find(i)])
        {
            printf("NIE\n");
            return 0;
        }
    }
    printf("TAK\n");
    return 0;
}

  

posted @ 2015-05-23 10:46  waterfull  阅读(407)  评论(0编辑  收藏  举报