备用交换机(tarjan求割点)

备用交换机

问题描述:
n个城市之间有通讯网络,每个城市都有通讯交换机,直接或间接与其它城市连接。因电子设备容易损坏,需给通讯点配备备用交换机。但备用交换机数量有限,不能全部配备,只能给部分重要城市配置。于是规定:如果某个城市由于交换机损坏,不仅本城市通讯中断,还造成其它城市通讯中断,则配备备用交换机。请你根据城市线路情况,计算需配备备用交换机的城市个数,及需配备备用交换机城市的编号。
输入格式:
第一行,一个整数n,表示共有n个城市(2<=n<=100)
下面有若干行,每行2个数a、b,a、b是城市编号,表示a与b之间有直接通讯线路。
输出格式:
第一行,1个整数m,表示需m个备用交换机,下面有m行,每行有一个整数,表示需配备交换机的城市编号,输出顺序按编号由小到大。如果没有城市需配备备用交换机则输出0。
输入输出样例
输入:
7
1 2
2 3
2 4
3 4
4 5
4 6
4 7
5 6
6 7
输出文件名:
2
2
4

思路:
tarjan算法求割点,注意判断根节点的情况。

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=110;
int n,m,tot,ans,head[maxn],root,gpoint[maxn];
int top,dfn[maxn],low[maxn],stack[maxn];
struct node
{
    int to;
    int next;
}e[maxn*maxn];
bool in[maxn];
void add_edge(int u,int v)
{
    tot++;
    e[tot].to=v;
    e[tot].next=head[u];
    head[u]=tot;
}
void tarjan(int u)
{
    int v;
    dfn[u]=low[u]=++tot;
    stack[++top]=u;
    in[u]=1;
    for(int i=head[u];i;i=e[i].next)
    {
        v=e[i].to;
        if(!dfn[v])
        {
            tarjan(v);
            low[u]=min(low[u],low[v]);
            if(low[v]>=dfn[u]&&u!=1)
            gpoint[u]++;
            else if(u==1)//特判根节点
            root++;
        }
        else if(in[v])
        low[u]=min(low[u],dfn[v]);
    }
    if(low[u]==dfn[u])
    {
        do
        {
            v=stack[top--];
            in[v]=0;

        }while(u!=v);
    }
}
int main()
{
    int x,y;
    cin>>n;
    while(cin>>x>>y)
    {
        m++;
        add_edge(x,y);
        add_edge(y,x);
    }tot=0;
    tarjan(1);
    if(root>1)//特判根节点
    ans++,gpoint[1]++;
    for(int i=2;i<=n;i++)
    if(gpoint[i])
    ans++;
    cout<<ans<<endl;
    for(int i=1;i<=n;i++)
    if(gpoint[i])
    cout<<i<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/cax1165/p/6070966.html