1. 程式人生 > >【洛谷P2341】[HAOI2006]受歡迎的牛

【洛谷P2341】[HAOI2006]受歡迎的牛

names () long 整數 struct code log 代碼 main

題目描述

每頭奶牛都夢想成為牛棚裏的明星。被所有奶牛喜歡的奶牛就是一頭明星奶牛。所有奶

牛都是自戀狂,每頭奶牛總是喜歡自己的。奶牛之間的“喜歡”是可以傳遞的——如果A喜

歡B,B喜歡C,那麽A也喜歡C。牛欄裏共有N 頭奶牛,給定一些奶牛之間的愛慕關系,請你

算出有多少頭奶牛可以當明星。

輸入輸出格式

輸入格式:

? 第一行:兩個用空格分開的整數:N和M

? 第二行到第M + 1行:每行兩個用空格分開的整數:A和B,表示A喜歡B

輸出格式:

? 第一行:單獨一個整數,表示明星奶牛的數量

輸入輸出樣例

輸入樣例#1:
3 3
1 2
2 1
2 3
輸出樣例#1:
1

說明

只有 3 號奶牛可以做明星

【數據範圍】

10%的數據N<=20, M<=50

30%的數據N<=1000,M<=20000

70%的數據N<=5000,M<=50000

100%的數據N<=10000,M<=50000

分析

知識點:強連通分量縮點tarjan算法的裸題。

縮點之後整個圖肯定是一顆樹,只要找到出度為零的那個縮點裏所包含點的個數就行了。

如果出度>1,是肯定沒有答案的。

為什麽是>1,因為當=0時,也就是整個圖都在一個連通分量中,此時所有點都是可以的。

數組盡量開大一點,因為A,B的範圍並沒有給,如果A,B太大的話就要用到離散化。

代碼

#include<iostream>
#include
<cstring> #include<cstdio> #include<algorithm> using namespace std; const int maxn=100000+5; inline int read() { int x=0,f=1; char ch=getchar(); while(ch<0||ch>9){if(ch==-)f=-1; ch=getchar();} while(ch>=0&&ch<=9){x=x*10+ch-0;ch=getchar();} return
x*f; } int n,m,tot,idx,top,cnt,ans,k; int head[maxn],u[maxn],v[maxn],du[maxn]; int dfn[maxn],low[maxn],sta[maxn],belong[maxn],num[maxn]; bool ins[maxn]; struct node { int next,to; }e[maxn*5]; inline void add(int from,int to) { e[++tot].next=head[from]; e[tot].to=to; head[from]=tot; } void tarjan(int x) { dfn[x]=low[x]=++idx; sta[++top]=x; ins[x]=1; for(int i=head[x];i;i=e[i].next) { int to=e[i].to; if(!dfn[to]) { tarjan(to); low[x]=min(low[x],low[to]); }else if(ins[to]) low[x]=min(low[x],dfn[to]); } if(dfn[x]==low[x]) { int y; cnt++; do { y=sta[top--]; ins[y]=0; belong[y]=cnt; num[cnt]++; }while(x!=y); } } int main() { n=read();m=read(); for(int i=1;i<=m;i++) { u[i]=read();v[i]=read(); add(u[i],v[i]); } for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i); for(int i=1;i<=m;i++) if(belong[u[i]]!=belong[v[i]]) du[belong[u[i]]]++; for(int i=1;i<=cnt;i++) if(!du[i]) k++,ans=num[i]; if(k>1) {printf("%d\n",0);return 0;} printf("%d\n",ans); return 0; }

【洛谷P2341】[HAOI2006]受歡迎的牛