POJ 2186 Popular Cows
2016-06-11 11:26
483 查看
Popular Cows
Time Limit: 2000MS | Memory Limit: 65536KB | 64bit IO Format: %I64d & %I64u |
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 ispopular, 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 12 3
Sample Output
1
Hint
Cow 3 is the only cow of high popularity.Source
USACO 2003 Fall
由于popular可以传递,所以可以把奶牛之间的关系看做一个有向图。为了处理方便,把这个图中的每个强连通分量看做一个整体(缩点)。
缩点之后的图是一个有向无环图(必然无环,因为如果有环,环可以继续缩)
在这个新图里找出度为0的点,如果出度为0的点只有一个,那么这个点对应的强连通分量里所有的奶牛都满足题意,如果出度为0的点有多个,那么无解(想一想为什么)
tarjan算法解如下:
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> #include<vector> #include<cstring> using namespace std; const int mxn=12000; int n,m; vector <int> e[mxn]; int dfn[mxn],low[mxn]; int st[mxn],top; bool inst[mxn]; int vis[mxn]; int dtime=0; int cnt=0; int belone[mxn],num[mxn]; int out[mxn]; void tarjan(int u){ int v,i; dfn[u]=++dtime; low[u]=dtime; inst[u]=true; st[++top]=u; for(i=0;i<e[u].size();i++){ v=e[u][i]; if(dfn[v]==-1){ tarjan(v); low[u]=min(low[u],low[v]); } else if(inst[v]){ low[u]=min(low[u],dfn[v]); } } if(dfn[u]==low[u]){ cnt++; do{ i=st[top--]; inst[i]=false; belone[i]=cnt; num[cnt]++; }while(i!=u); } // printf("test cnt:%d\n",cnt); return; } void solve(){ int i,j; for(i=1;i<=n;i++){ for(j=0;j<e[i].size();j++){ // printf("test: u:%d v:%d belone[v]:%d\n",i,e[i][j],belone[e[i][j]]); if(belone[i]!=belone[e[i][j]])out[belone[i]]++;//计算出度 } } int flag=0,mark; for(i=1;i<=cnt;i++){ if(out[i]==0)flag++,mark=i; } if(flag==1){ printf("%d\n",num[mark]); } else printf("0\n"); return; } int main(){ scanf("%d%d",&n,&m); int u,v; int i,j; for(i=1;i<=m;i++){ scanf("%d%d",&u,&v); e[u].push_back(v); } memset(dfn,-1,sizeof(dfn));//dfn初始化 for(i=1;i<=n;i++){ if(dfn[i]==-1)tarjan(i); } solve(); return 0; }
相关文章推荐
- .htaccess Rewrite apache重写和配置
- Hadoop HDFS 学习(2)理论
- SHELL编程之特殊符号
- poj2186 popular cows
- 一个 Linux 驱动的微波炉
- 使用Docker搭建ELK日志搜集系统(二)
- Linux 目录
- Linux 文本管理
- linux配置jdk
- Tomcat根目录下work文件夹的作用(转载)
- 构建高并发高可用的电商平台架构实践
- ant安装使用指南
- SHELL编程之执行环境
- ie和chrome浏览器下onproperty事件的相应和相应属性的获取
- Linux RPM软件包
- Linux 进程管理
- pixhawk的源码结构介绍(针对ArduCopter这套源码)(一)
- hadoop & hive任务优化之数据详情预知
- Linux IP配置
- linux下php上传文件注意事项