# Network of Schools（POJ 1236）(强连通+缩点)（Tarjan算法）

177人阅读 评论(0)

http://acm.hust.edu.cn/vjudge/problem/17001

1、有向无环图中所有入度不为0的点，一定可以由某个入度为0的点出发可达。

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>

using namespace std;

const int maxn = 200;
const int maxm = 10010;

struct Edge{
int to, next;
}edge[maxm];

int low[maxn], dfn[maxn], Stack[maxn], Belong[maxn];
int Index, top;
int scc;
bool Instack[maxn];
int num[maxn];
int n;

{
edge[tot].to = v;
}

void Tarjan(int u)
{
int v;
low[u] = dfn[u] = ++Index;
Stack[top++] = u;
Instack[u] = true;
for (int i = head[u]; i != -1; i = edge[i].next) {
v = edge[i].to;
if (!dfn[v]) {
Tarjan (v);
if (low[u] > low[v]) low[u] = low[v];
} else if (Instack[v] && low[u] > dfn[v]) low[u] = dfn[v];
}
if (low[u] == dfn[u]) {
scc++;
do{
v = Stack[--top];
Instack[v] = false;
Belong[v] = scc;
num[scc]++;
} while (v != u);
}
}

void solve(int n)
{
memset (dfn, 0, sizeof(dfn));
memset (Instack, false ,sizeof(Instack));
memset (num, 0, sizeof(num));
Index  = scc = top = 0;
for (int i = 1; i <= n; i++) {
if (!dfn[i]) Tarjan (i);
}
if (scc == 1) {
printf ("1\n0\n");
} else {
int in[maxn], out[maxn];
memset (in, 0, sizeof(in));
memset (out, 0, sizeof(out));

//Á´Ê½Ç°ÏòÐÇ
for (int u = 1; u <= n; u++) {
for (int i = head[u]; i != -1; i = edge[i].next) {
int v = edge[i].to;
if (Belong[u] != Belong[v]) {
in[Belong[v]]++;
out[Belong[u]]++;
//printf ("x%d->x%d\n", u, v);
}
}
}
int ans1 = 0, ans2= 0;
for (int i = 1; i <= scc; i++) {
if (!in[i]) ans1++;
if (!out[i]) ans2++;
}
printf ("%d\n%d\n", ans1, max (ans1, ans2));
}
}

void init()
{
tot = 0;
}

int main()
{
#ifndef ONLINE_JUDGE
freopen ("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
scanf ("%d", &n);
init ();
for (int i = 1; i <= n; i++) {
int Re;
while (scanf ("%d", &Re) != EOF) {
if (Re == 0) break;
}
}
solve (n);
return 0;
}

0
0

个人资料
• 访问：27213次
• 积分：1354
• 等级：
• 排名：千里之外
• 原创：109篇
• 转载：13篇
• 译文：1篇
• 评论：2条
阅读排行
最新评论