POJ1236 Network of Schools【强连通】

题意:

N(2<N<100)各学校之间有单向的网络,每个学校得到一套软件后,可以通过单向网络向周边的学校传输,问题1:初始至少需要向多少个学校发放软件,使得网络内所有的学校最终都能得到软件。2,至少需要添加几条传输线路(边),使任意向一个学校发放软件后,经过若干次传送,网络内所有的学校最终都能得到软件。

思路:

我们可以先进行缩点求出DAG图,然后我们考虑第一个问题,求最少发几套软件可以全覆盖,首先题意已经保证了是连通的。然后我们可以想,如果我们把所有没有入边的点都放上软件,是一定可行的。有入边的一定会通过一些边最终从一定有出边的发放软件的地方获得软件。然后我们考虑第二个问题:这是一个连通图,如果我们有些点没有入点,有些点没出点,那我们如果想办法将入点和一些出点相连,就能保证最后会成为很多圆相连。这样子答案就是没有入边的点和没有出边的点的最大值。

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
using namespace std;
stack<int> dl;
const int maxn = 150000;
int head[maxn],to[maxn],nxt[maxn],dfn[maxn],low[maxn],ins[maxn],sg[maxn];
int oud[maxn],ind[maxn];
int cnt,n,a,tot,tjs;

void ad_edg(int x,int y)
{
    nxt[++tjs] = head[x];
    head[x] = tjs;
    to[tjs] = y;
}

void sread()
{
    cin>>n;
    for (int i = 1;i <= n;i++)
    {
        while (1)
        {
            cin>>a;
            if (!a) break;
            ad_edg(i,a);
        }
    }
}

void tarjan(int x)       //Tarjan算法
{
    dfn[x] = low[x] = ++cnt;
    dl.push(x),ins[x] = 1;
    for (int i = head[x];i;i = nxt[i])
    {
        if (!dfn[to[i]])
        {
            tarjan(to[i]);
            low[x] = min(low[x],low[to[i]]);
        }else if (ins[to[i]])
            low[x] = min(low[x],dfn[to[i]]);

    }
    if (low[x] == dfn[x])
    {
        sg[x] = ++tot;
        while (dl.top() != x) ins[dl.top()] = 0,sg[dl.top()] = tot,dl.pop();
        ins[x] = 0,dl.pop();
    }
}

void swork()
{
    for (int i = 1;i <= n;i++)
        if (!dfn[i]) tarjan(i);
    for (int i = 1;i <= n;i++)
        for (int j = head[i];j;j = nxt[j])
            if (sg[i] != sg[to[j]])
                oud[sg[i]]++,ind[sg[to[j]]]++;
    int t1 = 0,t2 = 0;
    for (int i = 1;i <= tot;i++)
    {
        if (!ind[i]) t1++;
        if (!oud[i]) t2++;
    }
    if (tot == 1)
        cout<<"1"<<endl<<"0"<<endl;
    else
        cout<<t1<<endl<<max(t2,t1)<<endl;
}

int main()
{
    sread();
    swork();
    return 0;
}
View Code

 

posted @ 2017-10-09 16:59  codeg  阅读(119)  评论(0编辑  收藏  举报