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

POJ-2186 Popular Cows (强连通缩点)

2013-04-18 08:39 323 查看
Popular Cows

Time Limit: 2000MSMemory Limit: 65536K
Total Submissions: 18813Accepted: 7570
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.
Source

USACO 2003 Fall

思路:

  强连通缩点之后统计出度为0的节点是否唯一,若唯一则有解,统计该节点中真正包含的节点个数几位所求。

我把POJ中讨论区中提供的数据都通过了,一直WA,不知道哪错了。。。但是基本算法都是对的。

// OJ 测试 WA 代码

#include <cstdio>
#include <iostream>
#include <stack>

using namespace std;

const int MAX = 10005;
int n, m, cnt, order;
int dfn[MAX], low[MAX], out[MAX], belong[MAX];
bool instack[MAX];
stack<int> S;

struct edge
{
int num;
struct edge *next;
}head[MAX];

int min(int a, int b)
{
return a < b ? a : b;
}

void init()
{
for(int i = 1; i <= n; ++i)
head[i].next = NULL;
memset(low, 0, sizeof(low));
memset(dfn, 0, sizeof(dfn));
memset(out, 0, sizeof(out));
memset(instack, false, sizeof(instack));

while(!S.empty())
S.pop();
cnt = 0;   // 记录强连通分量的个数
order = 0;  //  时间戳
}

void targan(int u)
{
int v;
dfn[u] = low[u] = order++;
instack[u] =true;
S.push(u);
edge *t = head[u].next;
for(; t != NULL; t = t->next)
{
if(!dfn[t->num])
{
targan(t->num);
low[u] = min(low[u], low[t->num]);
}
else if(instack[t->num])
low[u] = min(low[u], dfn[t->num]);
}
if(dfn[u] == low[u])
{
++cnt;    // cnt 记录强连通分量的个数
do
{
v = S.top();
S.pop();
instack[v] = false;
belong[v] = cnt;
}while(v != u);
}
}

int solve()
{
edge *t;
for(int i = 1; i <= n; ++i)
{
t = head[i].next;
for(; t != NULL; t = t->next)
{
if(belong[i] != belong[t->num])
{
++out[belong[i]];
}
}
}
int tmp = 0;
int flag;
for(int i = 1; i <= cnt; ++i)
{
if(out[i] == 0)
{
++tmp;
flag = i;
}
}
if(tmp > 1)  //  缩点后出度为0的节点有多个时候,则不连通,即不存在最受欢迎的牛
return 0;
int ans = 0;
for(int j = 1; j <= n; ++j)//统计唯一的出度为0的节点中真正节点的个数
if(belong[j] == flag)
++ans;
return ans;
}

int main()
{
int a, b;
edge *tmp;
while(~scanf("%d%d", &n, &m))
{
init();
while(m--)
{
scanf("%d%d", &a, &b);
tmp = new edge;
tmp->num = b;
tmp->next = head[a].next;
head[a].next = tmp;
}
for(int i = 1; i <= n; ++i)
{
if(!dfn[i])
targan(i);
}
printf("%d\n", solve());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: