洛谷 P2746 [USACO5.3]校园网Network of Schools(tarjan(缩点)) 题解

题目来源:

https://www.luogu.org/problemnew/show/P2746

题目描述:

 

题目描述

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

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

输入输出格式

输入格式:

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

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

输出格式:

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

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

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

输入输出样例

输入样例#1: 复制

5
2 4 3 0
4 5 0
0
0
1 0

输出样例#1: 复制

1
2

说明

题目翻译来自NOCOW。

USACO Training Section 5.3

解题思路:

     这题是poj上的一题,tarjan缩点的经典题,现将图进行缩点,然后入度为0的分量就是第一问的答案,因为没有点可以到入度为0的点,第二问的答案就是max(入度为0,出度为0),因为要使任意点出发可到达,我们可以从出度为0向入度为0连边,显然这样最优。。。

代码:

#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
const int maxn=105;
struct newt{int to,next;}e[maxn*maxn];
int dfn[maxn],low[maxn],vis[maxn],n,tot,lt[maxn],head[maxn],rd[maxn],cd[maxn],gs,cnt;
void addedge(int u,int v)
{
    e[cnt].to=v;
    e[cnt].next=head[u];
    head[u]=cnt++;
}
stack <int> s;
void tarjan(int u)
{
    dfn[u]=low[u]=++tot;
    s.push(u);vis[u]=1;
    for(int i=head[u];i!=-1;i=e[i].next)
    {
        int v=e[i].to;
        if(!dfn[v]){
            tarjan(v);
            low[u]=min(low[u],low[v]);
        }
        else if(vis[v]){
            low[u]=min(low[u],dfn[v]);
        }
    }
    if(dfn[u]==low[u]){
        gs++;
        while(1)
        {
            int now=s.top();s.pop();
            //cout<<now<<" ";
            vis[now]=0;
            lt[now]=gs;
            if(now==u)break;
        }
        //cout<<endl;
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n;
    memset(head,-1,sizeof(head));
    gs=cnt=0;tot=0;
    for(int i=1;i<=n;i++)
    {
        int t;
        while(cin>>t&&t)
        {
            addedge(i,t);
        }
    }
    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!=-1;j=e[j].next)
        {
            int v=e[j].to;
            if(lt[i]==lt[v])continue;
            cd[lt[i]]++;
            rd[lt[v]]++;
        }
    }
    int sum1=0,sum2=0;
    for(int i=1;i<=gs;i++)
    {
        if(cd[i]==0)sum1++;
        if(rd[i]==0)sum2++;
    }
    if(gs==1){
        cout<<1<<endl;
        cout<<0<<endl;
    }
    else{
        cout<<sum2<<endl;
        cout<<max(sum1,sum2)<<endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40400202/article/details/81431642
今日推荐