poj 2186 Popular Cows 强连通分量
来源:互联网 发布:育儿软件有哪些 编辑:程序博客网 时间:2024/06/01 07:35
题目链接
http://poj.org/problem?id=2186
题意:
一群牛中,每个牛都有自己认为的受欢迎的牛,如果A认为B受欢迎,B认为C受欢迎,那么A也会认为C受欢迎。问题来了:给定一个牛之间受欢的关系图,牛用1~n的数代替。找出所有的受n头牛欢迎的牛,输出它们所代表的数字。
思路
一道有情景的题目,蛮有意思的但就是想不出(╥╯^╰╥)。看了题解又觉得简单。
受所有欢迎,在图中就是所有点都能够到达的点,如果图是强连通图,那么每头牛都是。如果有强连通分量,缩点后会形成dag,要求所有点都能到达某个点,所以这个点一定是在dag中的“末端”,也就是出度为0点的。但是如果有多个就不符合题意了,因为dag肯定不会有环,两个出度为0的点间不会连通。所以在dag中,如果有大于1个出度为0的点,答案为0.如果只有一个,答案就是这个强连通分量所代表的所有点。
#include<cstdio> // 强连通缩点:求出DAG中:出度为0的点#include<queue>#include<iostream>#include<vector>#include<map>#include<cstring>#include<string>#include<set>#include<stack>#include<algorithm>#define cle(a) memset(a,0,sizeof(a))#define inf(a) memset(a,0x3f,sizeof(a))#define ll long long#define Rep(i,a,n) for(int i=a;i<=n;i++)using namespace std;const int INF = ( 2e9 ) + 2;const ll maxn = 1e4+10;vector<int> g[maxn];int time,num;int dfn[maxn],low[maxn],instack[maxn],Out[maxn],scc[maxn];stack<int> s;void tarjan(int u){ dfn[u]=low[u]=++time; instack[u]=1; s.push(u); for(int i=0;i<g[u].size();i++) { int v=g[u][i]; if(!dfn[v]) { tarjan(v); low[u]=min(low[u],low[v]); } else if(instack[v]) low[u]=min(low[u],low[v]); } if(low[u]==dfn[u]) { num++; int x; do { x=s.top();s.pop(); instack[x]=0; scc[x]=num; }while(x!=u); }}int main(){ int n,m; while(~scanf("%d%d",&n,&m)) { time=num=0; while(!s.empty())s.pop(); memset(dfn,0,sizeof(dfn)); memset(low,0,sizeof(low)); memset(Out,0,sizeof(Out)); for(int i=1;i<=n;i++)g[i].clear(); for(int i=0;i<m;i++) { int u,v; scanf("%d%d",&u,&v); g[u].push_back(v); } for(int i=1;i<=n;i++) if(!dfn[i])tarjan(i); for(int i=1;i<=n;i++) for(int j=0;j<g[i].size();j++) { if(scc[i]!=scc[g[i][j]]) Out[scc[i]]++; } int ans=0,cnt=0; for(int i=1;i<=n;i++) if(Out[scc[i]]==0)ans++; for(int i=1;i<=num;i++) if(Out[i]==0)cnt++; if(cnt>=2) printf("0\n"); else printf("%d\n",ans); }}
阅读全文
0 0
- POJ 2186-Popular Cows ---强连通分量
- POJ 2186 Popular Cows / 强连通分量
- POJ 2186 Popular Cows 强连通分量
- POJ 2186 Popular Cows (强连通分量)
- POJ 2186 Popular Cows (强连通分量)
- POJ 2186 Popular Cows (强连通分量)
- POJ 2186 Popular Cows 强连通分量
- POJ 2186 Popular Cows 强连通分量
- poj 2186 Popular Cows 强连通分量
- POJ 2186 Popular Cows(强连通分量)
- poj 2186 Popular Cows 【强连通分量】
- |poj 2186|强连通分量|Popular Cows
- poj 2186 Popular Cows 强连通分量
- POJ 2186 Popular Cows (强连通分量)
- 【POJ】2186.Popular Cows--强连通分量
- poj 2186 Popular Cows (强连通分量,缩点)
- poj 2186 Popular Cows (强连通分量 tarjan)
- POJ 2186 Popular Cows (强连通分量)
- Oracle 的 SQL语句中如何处理‘&’等特殊符号
- ajax接收后台传来的JSON类型数据,可通过循环遍历为input赋值(input的ID需要和返回来的数据名相同)
- 仿美团炫酷动画效果的A-Z字母排序侧边库1
- coursera《机器学习》吴恩达-week2-01 多个变量的线性回归
- 用Java编写CGI小结
- poj 2186 Popular Cows 强连通分量
- 大整数的四则运算
- 2.串口通信的基本概念
- easyUI的常用API
- scanf_s()读入字符串和数字
- jquery 解决ie9及以下版本不支持placeholder属性
- APP接口自动化测试JAVA+TestNG小实例
- Xshell能ping通Debian系统却无法连接
- linux命令执行返回值