首页 > 代码库 > POJ——T2186 Popular Cows || 洛谷——P2341 [HAOI2006]受欢迎的牛

POJ——T2186 Popular Cows || 洛谷——P2341 [HAOI2006]受欢迎的牛

http://poj.org/problem?id=2186

||

https://www.luogu.org/problem/show?pid=2341

Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 33470 Accepted: 13634

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 31 22 12 3

Sample Output

1

Hint

Cow 3 is the only cow of high popularity. 

Source

USACO 2003 Fall

tarjan缩点,输出入度为0的点的子图中的点的个数

 1 #include <algorithm> 2 #include <cstring> 3 #include <cstdio> 4  5 using namespace std; 6  7 const int N(50015); 8 int n,m,u,v,sumchudu,ans,cnt; 9 int point[N],chudu[N];10 int sumedge,head[N];11 struct Edge12 {13     int from,to,next;14     Edge(int from=0,int to=0,int next=0) :15     from(from),to(to),next(next) {}16 }edge[N];17 18 int ins(int from,int to)19 {20     edge[++sumedge]=Edge(from,to,head[from]);21     return head[from]=sumedge;22 }23 24 int dfn[N],low[N],tim;25 int Stack[N],top,instack[N];26 int col[N],sumcol;27 28 void DFS(int now)29 {30     dfn[now]=low[now]= ++tim;31     Stack[++top]=now; instack[now]=1;32     for(int i=head[now];i;i=edge[i].next)33     {34         v=edge[i].to;35         if(instack[v]) low[now]=min(low[now],dfn[v]);36         else if(!dfn[v])37               DFS(v), low[now]=min(low[now],low[v]);38     }39     if(low[now]==dfn[now])40     {41         col[now]= ++sumcol;42         point[sumcol]++;43         for(;Stack[top]!=now;top--)44         {45             point[sumcol]++;46             col[Stack[top]]=sumcol;47             instack[Stack[top]]=0;48         }49         instack[now]=0; top--;50     }51 }52 53 int main()54 {55     scanf("%d%d",&n,&m);56     for(int i=1;i<=m;i++)57         scanf("%d%d",&u,&v),ins(u,v);58     for(int i=1;i<=n;i++)59         if(!dfn[i]) DFS(i);60     for(int i=1;i<=m;i++)61     {62         u=edge[i].from; v=edge[i].to;63         if(col[u]!=col[v]) chudu[col[u]]++;64     }65     for(int i=1;i<=sumcol;i++) if(!chudu[i])66         ++sumchudu,ans=point[i];67     if(sumchudu!=1) ans=0;68     printf("%d\n",ans);69     return 0;70 }

 

POJ——T2186 Popular Cows || 洛谷——P2341 [HAOI2006]受欢迎的牛