【POJ - 2186】Popular Cows (Tarjan缩点)
題干:
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 3Sample Output
1Hint
Cow 3 is the only cow of high popularity.?
題目大意:
有N(N<=10000)頭牛,每頭牛都想成為most poluler的牛,給出M(M<=50000)個關系,如(1,2)代表1歡迎2,關系可以傳遞,但是不可以相互,即1歡迎2不代表2歡迎1,但是如果2也歡迎3那么1也歡迎3.
給出N,M和M個歡迎關系,求被所有牛都歡迎的牛的數量。
解題報告:
? Tarjan縮點然后看集合數量是否是1,如果不是1那就輸出0,如果是1,那就輸出這個集合的數量。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair using namespace std; const int MAX = 2e5 + 5; int n,m; int head[MAX]; int DFN[MAX],LOW[MAX],col[MAX],cnt[MAX],stk[MAX],out[MAX]; bool vis[MAX]; struct Edge {int fr,to,ne; } e[MAX],ee[MAX]; int tot,tot2,timing,scc,index; void add(int u,int v) {e[++tot].fr = u;e[tot].to = v;e[tot].ne = head[u];head[u] = tot; } void Tarjan(int x) {LOW[x] = DFN[x] = ++timing;vis[x] = 1;stk[++index] = x;for(int i = head[x]; i!=-1; i=e[i].ne) {int v = e[i].to;if(!DFN[v]) {Tarjan(v);LOW[x] = min(LOW[x],LOW[v]);}else if(vis[v]) {LOW[x] = min(LOW[x],DFN[v]);}}if(DFN[x] == LOW[x]) {scc++;while(1) {int tmp = stk[index];index--;vis[tmp]=0;col[tmp] = scc;cnt[scc]++;if(x == tmp) break;}} } int main() {cin>>n>>m;memset(head,-1,sizeof head);for(int a,b,i = 1 ; i<=m; i++) {scanf("%d%d",&a,&b);add(a,b);}for(int i = 1; i<=n; i++) {if(!DFN[i]) Tarjan(i);}for(int i = 1; i<=m; i++) {if(col[e[i].fr] != col[e[i].to]) {out[col[e[i].fr]]++;}} // for(int u = 1; u<=n; u++) { // for(int i = head[u]; i!=-1; i=e[i].ne) { // int v = e[i].to; // if(col[u] != col[v]) out[] // } // }int emmm=0,ans=0;for(int i = 1; i<=scc; i++) {if(out[i] == 0) {emmm++;ans = cnt[i];} }if(emmm != 1) printf("0\n");else printf("%d\n",ans);return 0 ; }?
總結
以上是生活随笔為你收集整理的【POJ - 2186】Popular Cows (Tarjan缩点)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我国2019年GDP,最终核算少了4千多
- 下一篇: 信用卡逾期多久上征信 巧用“容时容差”远