Popular Cows
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 23420 | Accepted: 9593 |
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.
Source
用kosaraju算法(具体参见算法训练指南第320页)算出强连通分量,保存在scc(值相同的属于同一个强连通分量)中。
把每一个强联通分量看成一个点(这样就构成了一个有k个点的有向无环图DAG),这样就有1-k个点,其中第k个点为出度为0的点。
如果出度为0的点>=2说明不存在题目要求的点,如果出度为0的点==1,则说明第k个联通分量中中所有的点就是是题目所求点个数。所以可以从第k个点中的任意一个点出发dfs,若有不可达点,则为0,若均可达,则为第k个联通分量中所有的点。
AC代码:
#include<cstring>
#include<algorithm>
#include<stdio.h>
#include<iostream>
#include<vector>
using namespace std;
int n;
int vis[10010],scc[10010];
vector <int> G1[10010],G2[10010],s;
void dfs(int u){
vis[u]=1;
for(int i=0;i<G2[u].size();i++){
if(!vis[G2[u][i]])
dfs(G2[u][i]);
}
}
void dfs1(int u){
vis[u]=1;
for(int i=0;i<G1[u].size();i++){
if(!vis[G1[u][i]])
dfs1(G1[u][i]);
}
s.push_back(u);
}
void dfs2(int u,int k){
scc[u]=k;
for(int i=0;i<G2[u].size();i++){
if(!scc[G2[u][i]])
dfs2(G2[u][i],k);
}
}
int find_scc(){
int k=0;
s.clear();
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++){
if(!vis[i])
dfs1(i);
}
memset(scc,0,sizeof(scc));
for(int i=s.size()-1;i>=0;i--){
if(!scc[s[i]]){
dfs2(s[i],++k);
}
}
return k;
}
int main(){
int T;
while(scanf("%d%d",&n,&T)!=EOF){
for(int i=1;i<=n;i++){
G1[i].clear();
G2[i].clear();
}
while(T--){
int x,y;
scanf("%d%d",&x,&y);
G1[x].push_back(y);
G2[y].push_back(x); //保存逆图
}
int num,v;
int k=find_scc();
num=0;
for(int i=1;i<=n;i++){
if(scc[i]==k){
v=i;
num++;
}
}
memset(vis,0,sizeof(vis));
dfs(v);
for(int i=1;i<=n;i++){
if(!vis[i]){
num=0;
break;
}
}
printf("%d\n",num);
}
return 0;
}