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

Popular Cows

2015-09-07 20:21 351 查看
Popular Cows

Time Limit: 2000MSMemory Limit: 65536K
Total Submissions: 27607Accepted: 11109
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 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 3

Sample Output

1

Hint

Cow 3 is the only cow of high popularity.
题意:判断有多少牛是其他牛都受欢迎的。由于关系太多太复杂,连通图内连通分量性质一样,所以先划分联通区域。一个连通图缩成一点处理,有向无环图出度为0的连通分量内的点数为受欢迎牛的个数。

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

#define N 10008

int Time, cnt, tot, top;
int dfn
, low
, instack
, stackk
, head
;
int vis
, id
;

struct node
{
int u, v, next;
}e[N*5];   // 邻接表

void add(int a, int b)
{
e[cnt].u = a;
e[cnt].v = b;
e[cnt].next = head[a];
head[a] = cnt;
cnt++;
}

void init()
{
tot = cnt = top = 0;
Time = 0;
memset(dfn, 0, sizeof(dfn));
memset(low, 0, sizeof(low));
memset(instack, 0, sizeof(instack));
memset(stackk, 0, sizeof(stackk));
memset(head, -1, sizeof(head));
memset(vis, 0, sizeof(vis));
memset(id, 0, sizeof(id));
}

void Tarjan(int u)
{
low[u] = dfn[u] = ++Time;
instack[u] = 1;
stackk[top++] = u;

for(int i = head[u]; i != -1; i = e[i].next)
{
int v = e[i].v;
if(!dfn[v])
Tarjan(v);
if(instack[v])
low[u] = min(low[v], low[u]);
}
int v;
if(low[u] == dfn[u])  // 找到一个连通分量
{
tot++;  // 强连通分量计数
do
{
v = stackk[--top];
instack[v] = 0;
id[v] = tot;
}while(v != u);
}
}

int main()
{
int n, m, x, y;
while(~scanf("%d%d", &n, &m))
{
init();
while(m--)
{
scanf("%d%d", &x, &y);
add(x, y);
}
for(int i = 1; i <= n; i++)
{
if(!dfn[i])
Tarjan(i);
}
int sum = 0, x;

for(int i = 1; i <= n; i++)
{
for(int j = head[i]; j != -1; j = e[j].next)
{
int q = e[j].v;
if(id[i] != id[q])  // 如果这两个点不属于一个强连通分量,就把 i 所在强连通分量的出度加一
{
vis[id[i]]++;
}
}
}
for(int i = 1; i <= tot; i++)
{
if(!vis[i])
{
sum++;
x = i;  // 记录哪个强连通分量是出度为0的图
}
}
if(sum == 1)
{
sum = 0;
for(int i = 1; i <= n; i++)
{
if(id[i] == x)  // 出度为0的连通分量内的点计数
sum++;
}
printf("%d\n", sum);
}
else
printf("0\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: