P2746 [USACO5.3]校园网Network of Schools Tarjan + 缩点

题目描述

一些学校连入一个电脑网络。那些学校已订立了协议:每个学校都会给其它的一些学校分发软件(称作“接受学校”)。注意即使 B 在 A 学校的分发列表中, A 也不一定在 B 学校的列表中。

你要写一个程序计算,根据协议,为了让网络中所有的学校都用上新软件,必须接受新软件副本的最少学校数目(子任务 A)。更进一步,我们想要确定通过给任意一个学校发送新软件,这个软件就会分发到网络中的所有学校。为了完成这个任务,我们可能必须扩展接收学校列表,使其加入新成员。计算最少需要增加几个扩展,使得不论我们给哪个学校发送新软件,它都会到达其余所有的学校(子任务 B)。一个扩展就是在一个学校的接收学校列表中引入一个新成员。

输入格式:

输入文件的第一行包括一个整数 N:网络中的学校数目(2 <= N <= 100)。学校用前 N 个正整数标识。

接下来 N 行中每行都表示一个接收学校列表(分发列表)。第 i+1 行包括学校 i 的接收学校的标识符。每个列表用 0 结束。空列表只用一个 0 表示。

输出格式:

你的程序应该在输出文件中输出两行。

第一行应该包括一个正整数:子任务 A 的解。

第二行应该包括子任务 B 的解。

输入样例:
5
2 4 3 0
4 5 0
0
0
1 0
输出样例:
1
2

说明

题目翻译来自NOCOW。

USACO Training Section 5.3

题解:

缩点后入度为0的点不可被提供软件;

则 任务A 即为 求缩点后入度为0的个数;

则入度为0的点必须要被提供新的软件;

但出度若 > 0, 则可形成新的入度为0的点;

 任务B 即为 求入度为0的点数与出度为0的点的较大值;

 

#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
const int N = 1e2 + 5;
int n, ru[N], chu[N];
struct edge { int to, nxt; } e[10000];
int c, head[N];
void add(int from, int to) {
    e[++ c].to = to;
    e[c].nxt = head[from];
    head[from] = c;
}
stack <int> s;
int dfn[N], low[N], tot, scc, tar[N];
void tarjan(int x) {
    dfn[x] = low[x] = ++ tot;
    s.push(x);
    for(int i = head[x]; i ;i = e[i].nxt) {
        int to = e[i].to;
        if(! dfn[to]) {
            tarjan(to);
            low[x] = min(low[x], low[to]);
        }
        else if(! tar[to])
            low[x] = min(low[x], dfn[to]);
    }
    if(dfn[x] == low[x]) {
        scc ++;
        while(1) {
            int y = s.top(); s.pop();
            tar[y] = scc;
            if(y == x) break;
        };
    }
}
int main() {
    cin >> n;
    for(int i = 1, x;i <= n;i ++) {
        cin >> x;
        while( x ) add(i, x), cin >> x;
    }
    for(int i = 1;i <= n;i ++) if(! low[i]) tarjan(i);
    for(int x = 1;x <= n;x ++) {
        for(int i = head[x]; i ;i = e[i].nxt) {
            int y = e[i].to;
            if(tar[x] == tar[y]) continue;
            ru[tar[y]] ++, chu[tar[x]] ++;
        }
    }
    int inc = 0, outc = 0;
    for(int i = 1;i <= scc;i ++) {
        inc += ru[i] == 0 ? 1 : 0;
        outc += chu[i] == 0 ? 1 : 0;
    }
    if(scc == 1) cout << "1\n0" << endl;
    else cout << inc << endl << max(inc, outc) << endl;
    return 0;
}

 

posted @ 2019-07-22 20:25  Paranoid丶离殇  阅读(117)  评论(0编辑  收藏  举报