POJ 2186 Popular Cows(强联通+缩点)

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. 

题目大意:给n个点m条有向边,问有多少个点满足,所有其他点都有一条能到达它的路径。

思路:先用tarjan求强联通分量,缩点,形成树。若有且只有一个点(缩了之后)出度为0,那么所有其他点都能到达它(缩点之后形成的是一个树状结构,出度为0的点为根)。若不止一个点出度为零,说明答案为0(因为这些出度为0的点之间不能互相到达)。

代码(79MS):

 #include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std; const int MAXN = ;
const int MAXE = ; int outdeg[MAXN], pre[MAXN], lowlink[MAXN], sum[MAXN];
int head[MAXN], sccno[MAXN], ecnt, scc_cnt;
int to[MAXE], next[MAXE];
int n, m, dfs_clock;
int stk[MAXN], top; void init() {
memset(sum, , sizeof(sum));
memset(head, , sizeof(head));
memset(outdeg, , sizeof(outdeg));
ecnt = ;
scc_cnt = ;
dfs_clock = ;
} void add_edge(int u, int v) {
to[ecnt] = v; next[ecnt] = head[u]; head[u] = ecnt++;
} void dfs(int u) {//tarjan
pre[u] = lowlink[u] = ++dfs_clock;
stk[++top] = u;
for(int p = head[u]; p; p = next[p]) {
int &v = to[p];
if(!pre[v]) {
dfs(v);
if(lowlink[u] > lowlink[v]) lowlink[u] = lowlink[v];
} else if(!sccno[v]) {
if(lowlink[u] > pre[v]) lowlink[u] = pre[v];
}
}
if(lowlink[u] == pre[u]) {
++scc_cnt;
while(true) {
int x = stk[top--];
sccno[x] = scc_cnt;
if(x == u) break;
}
}
} int solve() {
for(int i = ; i <= n; ++i)
if(!pre[i]) dfs(i);
for(int u = ; u <= n; ++u) {
++sum[sccno[u]];
for(int p = head[u]; p; p = next[p]) {
int &v = to[p];
if(sccno[u] == sccno[v]) continue;
++outdeg[sccno[u]];
}
}
int ans = ;
for(int i = ; i <= scc_cnt; ++i)
if(outdeg[i] == ) {
if(ans == ) ans = sum[i];
else return ;
}
return ans;
} int main() {
scanf("%d%d", &n, &m);
init();
while(m--) {
int a, b;
scanf("%d%d", &a, &b);
add_edge(a, b);
}
printf("%d\n", solve());
}
上一篇:2013 Multi-University Training Contest 10


下一篇:【STM32】STM32 GPIO模式理解