题目链接:受欢迎的牛
分析
根据喜欢关系建图。任意一个强连通分量里面的牛都互相喜欢,于是就用tarjan缩点,然后将多个强连通分量又构成一个DAG
成为明星的条件就是出度为0。·不止一个的话就没有牛能成为明星。
上代码
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m,ans;
int dfn[10001],low[10001],col[10001],lv[10001];
int st[10001],top;
int du[10001],sum[10001];
int tot,hd[30001];
int tm,tt;
struct lwx
{
int to,next;
}e[100001];
void add(int x,int y)
{
e[++tot]=(lwx){y,hd[x]};
hd[x]=tot;
}
void tarjan(int x)
{
dfn[x]=low[x]=++tm;
st[++top]=x;
lv[x]=1;
for(int i=hd[x];i>0;i=e[i].next)
{
int y=e[i].to;
if(!dfn[y])
{
tarjan(y);
low[x]=min(low[x],low[y]);
}
else if(lv[y]) low[x]=min(low[x],dfn[y]);
}
if(dfn[x]==low[x])
{
col[x]=++tt;
sum[tt]++;
while(st[top]!=x)
{
col[st[top--]]=tt;
sum[tt]++;
}
top--;
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y;
cin>>x>>y;
add(x,y);
}
for(int i=1;i<=n;i++)
{
if(!dfn[i]) tarjan(i);
}
for(int i=1;i<=n;i++)
{
for(int j=hd[i];j>0;j=e[j].next)
{
int y=e[j].to;
if(col[i]!=col[y]) du[col[i]]++;
}
}
for(int i=1;i<=tt;i++)
{
if(!du[i]&&!ans) ans=i;
else if(!du[i]&&ans)
{
cout<<0;
return 0;
}
}
cout<<sum[ans];
return 0;
}