Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 28399 | Accepted: 9684 |
Description
There is exactly one node, called the root, to which no directed edges point.
Every node except the root has exactly one edge pointing to it.
There is a unique sequence of directed edges from the root to each node.
For example, consider the illustrations below, in which nodes are represented by circles and edges are represented by lines with arrowheads. The first two of these are trees, but the last is not.
In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not.
Input
the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero.
Output
Sample Input
6 8 5 3 5 2 6 4
5 6 0 0 8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0 3 8 6 8 6 4
5 3 5 6 5 2 0 0
-1 -1
Sample Output
Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree.
刚开始看到这题以为跟HDU上那个迷宫题目一样,后来发现是有向图,而那个迷宫是无向图。但是道理差不多。
判断一个有向图是否为树:无环;n个结点最多有n-1条边,不然就会有环;只有一个入度为0的结点,不存在入度大于1的结点
根据以上信息就可以判断一个有向图是否存在环,然后假设他是一个树对其进行拓扑排序。排序的点放入一个set中(一开始用queue就WA。估计是重复了什么吧。加上这题排序的顺序没用,set确实更适合于此题的记录个数因为不会重复)就这样搜搜搜就过了。这题看discuss是用并查集用的比较多,有时间用并查集做做。此题数据据说比较水,可能这代码也有问题。但是DISCUSS里那几个特例都是可以过的。
代码:
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#define INF 0x3f3f3f3f
#define MM(x) memset(x,0,sizeof(x))
using namespace std;
typedef long long LL;
const int N=100010;
vector<int>edge[N];//ÁÚ½Ó±í
map<int,int>deg;
int main(void)
{
int x,y,i,j,q=1;
int flag=1;
while (~scanf("%d%d",&x,&y))
{
if(x==-1&&x==y)
{
break;
}
else if(x==0&&y==0)
{
map<int,int>::iterator it;
queue<int> Q;
set<int>tp;
for (it=deg.begin(); it!=deg.end(); it++)
{
if(it->second==0)
{
Q.push(it->first);
tp.insert(it->first);
break;
}
}
while (!Q.empty())
{
int now=Q.front();
Q.pop();
for (i=0; i<edge[now].size(); i++)
{
int v=edge[now][i];
deg[v]--;
if(deg[v]==0)
{
tp.insert(v);
Q.push(v);
}
}
}
//cout<<deg.size()<<" "<<endl;
if(tp.size()==deg.size()&&flag)
printf("Case %d is a tree.\n",q++);
else
printf("Case %d is not a tree.\n",q++);
deg.clear();
for (i=0; i<N; i++)
edge[i].clear();
flag=1;
tp.clear();
while (!Q.empty())
Q.pop();
}
else
{
if(deg.find(x)==deg.end())
deg[x]=0;
deg[y]++;
if(deg[y]>=2)
flag=0;
edge[x].push_back(y);
}
}
return 0;
}