您的位置:首页 > 运维架构

poj 2186 Popular Cows

2015-11-02 20:00 253 查看

Popular Cows

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 10   Accepted Submission(s) : 4
[align=left]Problem Description[/align]
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.

 

[align=left]Input[/align]
* 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.

 

[align=left]Output[/align]
* Line 1: A single integer that is the number of cows who are considered popular by every other cow.

 

[align=left]Sample Input[/align]

3 3
1 2
2 1
2 3

 

[align=left]Sample Output[/align]

1
#include<stdio.h>
#include<string.h>
#include<stack>
#include<vector>
#define MAXN 10010
#define MAXM 50010
using namespace std;
vector<int>scc[MAXN];
vector<int> G[MAXN];
stack<int>s;
int dfn[MAXN];
int low[MAXN];
int edgenum,scc_cnt,dfn_clock;
int sccno[MAXN];
bool instack[MAXN];
int out[MAXM];//记录SCC的入度与出度
struct Edge
{
int from,to,next;
}edge[MAXM];
int head[MAXM];
void add(int u,int v)
{
Edge E={u,v,head[u]};
edge[edgenum]=E;
head[u]=edgenum++;
}
void tarjan(int u)
{
dfn[u]=low[u]=++dfn_clock;
s.push(u);
instack[u]=true;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(instack[v])
low[u]=min(low[u],dfn[v]);
}
if(low[u]==dfn[u])
{
scc_cnt++;
for(; ;)
{
int v=s.top();
s.pop();
instack[v]=false;
sccno[v]=scc_cnt;
scc[scc_cnt].push_back(v);
if(v==u)
break;
}

}
}
void inital()
{
edgenum=0;
scc_cnt=dfn_clock=0;
memset(head,-1,sizeof(head));
memset(sccno,0,sizeof(sccno));
memset(instack,false,sizeof(instack));
memset(scc,0,sizeof(scc));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
}
void find(int l,int r)
{
for(int i=l;i<=r;i++)
if(!dfn[i])
tarjan(i);
}
void suodian()
{
for(int i = 1; i <= scc_cnt; i++)
G[i].clear(),  out[i] = 0;
for(int i = 0; i < edgenum; i++)
{
int u = sccno[edge[i].from];
int v = sccno[edge[i].to];
if(u != v)
{
G[u].push_back(v);
out[u]++;
}
}
}
int main()
{
int m,n;
while(scanf("%d%d",&n,&m)!=EOF)
{
int u,v;
inital();
while(m--)
{
scanf("%d%d",&u,&v);
add(u,v);
}
find(1,n);
if(scc_cnt==1)
{
printf("%d\n",n);
continue;
}
suodian();
int i,count=0,t;
for(i=1;i<=scc_cnt;i++)
if(out[i])
count++;
else
t=i;
if(count==scc_cnt-1)
{
count=0;
for(i=1;i<=n;i++)
if(sccno[i]==t)
count++;
printf("%d\n",count);
}
else
printf("0\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: