排位赛2-Milk Factory
题目
The milk business is booming! Farmer John’s milk processing factory consists of N processing stations, conveniently numbered 1…N (1≤N≤100), and N−1 walkways, each connecting some pair of stations. (Walkways are expensive, so Farmer John has elected to use the minimum number of walkways so that one can eventually reach any station starting from any other station). To try and improve efficiency, Farmer John installs a conveyor belt in each of its walkways. Unfortunately, he realizes too late that each conveyor belt only moves one way, so now travel along each walkway is only possible in a single direction! Now, it is no longer the case that one can travel from any station to any other station.
However, Farmer John thinks that all may not be lost, so long as there is at least one station i such that one can eventually travel to station i from every other station. Note that traveling to station i from another arbitrary station j may involve traveling through intermediate stations between i and j. Please help Farmer John figure out if such a station i exists.
题意
又n个车站,又n-1条单向路,问是否存在一个站点所有其他站点都可以到达。
解法
数据范围很小所以直接dfs暴搜即可。
代码:
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <math.h>
using namespace std;
const int maxn=110;
struct CC
{
int next,to;
}edge[maxn];
int n,x,y,ans,cnt,head[maxn];
bool w[maxn][maxn],f[maxn];
void add(int x,int y)
{
edge[++cnt].next=head[x];
edge[cnt].to=y;
head[x]=cnt;
}
void dfs(int t,int x)
{
w[t][x]=true;
for (int i=head[x];i!=0;i=edge[i].next)
{
int v=edge[i].to;
if (f[v]) continue;
f[v]=true;
dfs(t,v);
f[v]=false;
}
}
int main()
{
scanf("%d",&n);
for (int i=1;i<n;i++)
{
scanf("%d%d",&x,&y);
add(x,y);
}
for (int i=1;i<=n;i++)
{
dfs(i,i);
}
ans=-1;
for (int i=1;i<=n;i++)
{
bool flag=true;
for (int j=1;j<=n;j++)
if (!w[j][i]) flag=false;
if (flag)
{
ans=i;
break;
}
}
printf("%d",ans);
return 0;
}