Description
Every cow's dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10,000) cows, you are given up to M (1 <= M <= 50,000) ordered pairs of the form (A, B) that tell you that
cow A thinks that cow B is popular. Since popularity is transitive, if A thinks B is popular and B thinks C is popular, then A will also think that C is
popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow.
popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow.
Input
* Line 1: Two space-separated integers, N and M
* Lines 2..1+M: Two space-separated numbers A and B, meaning that A thinks B is popular.
* Lines 2..1+M: Two space-separated numbers A and B, meaning that A thinks B is popular.
Output
* Line 1: A single integer that is the number of cows who are considered popular by every other cow.
Sample Input
3 3
1 2
2 1
2 3
Sample Output
1
Hint
Cow 3 is the only cow of high popularity.
题目大意:有 N 头牛,M 对关系(例如 A -> B)构成一个有向图,关系的含义为 A -> B 为牛 A 认为牛 B Good。关系间具有传递性,若有 A -> B 、B -> C,则有 A -> C。问有多少头牛被所有牛认为 Good。
强连通分量缩点的经典题目。有向图可以看成是由若干强连通分量构成的 DAG ,A 认为 B Good 可以看成 A 可以到 B 。每一个强连通分量内的点均互相可达,则任意与他们中的点的出边相连的点都是可达的。那么该 DAG(强连通分量缩点后的图) 中有且仅有一个出度为零的点时,该点对任意点而言都是可达的。那么题目转化为求强连通分量缩点后的 DAG 中是否存在唯一的点出度零。若存在,则该连通分量内的点数即为答案,否则答案为零。
一开始第二个 DFS 写挫了,T 了一晚上。。。
贴个代码以示教训:
#include<cstdio>
#include<algorithm>
#include<vector>
#include<stack>
#include<cstring>
using namespace std;
const int maxn = 1e4 + 5;
int n,m;
bool vis[maxn];
vector<int> v[maxn];
stack<int> s;
int cnt[maxn],pre[maxn],dev[maxn],out[maxn],sum[maxn];
int dfs_time = 1,cou = 1;
void DFS(int x)
{
int len = v[x].size();
dev[x] = pre[x] = dfs_time++;
s.push(x);
for(int i = 0;i < len; ++i)
{
int u = v[x][i];
if(!vis[u])
{
vis[u] = true;
DFS(u);
dev[x] = min(dev[x],dev[u]);
}
else if(!cnt[u]) dev[x] = min(dev[x],pre[u]);
}
if(pre[x] == dev[x])
{
int temp;
while(!s.empty())
{
temp = s.top();
s.pop();
cnt[temp] = cou;
++sum[cou];
if(temp == x) break;
}
++cou;
}
}
void Solve(int x)
{
int len = v[x].size();
for(int i = 0;i < len; ++i)
{
int u = v[x][i];
if(cnt[x] != cnt[u]) out[cnt[x]]++;
if(!vis[u])
{
vis[u] = true;
Solve(u);
}
}
}
int main()
{
scanf("%d %d",&n,&m);
int x,y;
for(int i = 0;i <= n; ++i)
{
cnt[i] = sum[i] = out[i] = 0;
vis[i] = false;
}
for(int i = 0;i < m; ++i)
{
scanf("%d %d",&x,&y);
v[x].push_back(y);
}
for(int i = 1;i <= n; ++i)
{
if(!vis[i])
{
vis[i] = true;
DFS(i);
}
}
memset(vis,false,sizeof(vis));
for(int i = 1;i <= n; ++i)
{
if(!vis[i])
{
vis[i] = true;
Solve(i);
}
}
int ans = 0,num = 0;
for(int i = 1;i < cou; ++i) if(!out[i]) ++num,ans = sum[i];
printf("%d\n",num == 1 ? ans : 0);
return 0;
}