Popular Cows
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. 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. 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 |
这道题就是把强连通分量分解,然后取出最末尾的那个分量看是否成立即可
#include<iostream>
#include<vector>
using namespace std;
const long max_v=10005;
vector<long>G[max_v];
vector<long>rG[max_v];
vector<long>vs;
long v,cmp[max_v],n,m;
bool used[max_v];
void add_edge(long from,long to)
{
G[from].push_back(to);
rG[to].push_back(from);
}
void dfs(long v)
{
used[v]=1;
for(long i=0;i<G[v].size();i++)
if(!used[G[v][i]])dfs(G[v][i]);
vs.push_back(v);
}
void rdfs(long v,long k)
{
used[v]=1;
cmp[v]=k;
for(long i=0;i<rG[v].size();i++)
if(!used[rG[v][i]])rdfs(rG[v][i],k);
}
long scc()
{
memset(used,0,sizeof(used));
vs.clear();
for(long v=0;v<n;v++)
if(!used[v])dfs(v);
memset(used,0,sizeof(used));
long k=0;
for(long i=vs.size()-1;i>=0;i--)
if(!used[vs[i]])rdfs(vs[i],k++);
return k;
}
int main()
{
cin>>n>>m;
for(long i=0;i<m;i++)
{
long f,t;
cin>>f>>t;
add_edge(f-1,t-1);
}
long x=scc(),ans=0,v;
// cout<<x<<endl;
for(long i=0;i<n;i++)
if(cmp[i]==x-1){ans++;v=i;}
memset(used,0,sizeof(used));
rdfs(v,0);
bool f=true;
for(long i=0;i<n;i++)
if(!used[i]){f=false;break;}
if(f)cout<<ans<<endl;else cout<<0<<endl;
// system("pause");
return 0;
}
。