poj1523(割點)


1.思路參考劉汝佳的算法藝術與信息學競賽。

2.代碼。

#include<cstdio>
#include<iostream>
using namespace std;
//   freopen("data.in","r",stdin);

#include<cstring>
#define N 1005
bool G[N][N];
int _V;
int root;
bool vis[N];
int deep[N],ancestor[N];
bool cutP[N];
//int son[N];
int cutE[N][N];
void init()
{
    memset(G,0,sizeof(G));
    memset(cutP,0,sizeof(cutP));
  //  memset(son,0,sizeof(son));
    memset(deep,-1,sizeof(deep));
    memset(vis,0,sizeof(vis));
    _V=2;
    root=1;
}
void dfs(int u,int father,int d)
{

    deep[u]=ancestor[u]=d;
    int son=0;
    for(int v=1; v<=_V; v++)
    {
        if(G[u][v])
        {
            if(deep[v]==-1)
            {
                son++;
                dfs(v,u,d+1);
                ancestor[u]=ancestor[u]>ancestor[v]?ancestor[v]:ancestor[u];
            }
            else if(v!=father)
            {
                ancestor[u]=ancestor[u]>deep[v]?deep[v]:ancestor[u];
            }
        }
    }
    if(u==root)
    {
        if(son>1)cutP[root]=true;
        else cutP[root]=false;
    }
    else if(ancestor[u]>=deep[father])//
    {
        cutP[father]=true;
        cutE[father][u]=true;
    }
}

void output(int Case)
{
    printf("Network #%d\n",Case);
    bool exist=false;

    for(int u=1; u<=_V; u++)
    {
        if(cutP[u])
        {
            exist=true;
            int branch;
            if(u==1)branch=0;
            else branch=1;
            bool f=false;
            for(int v=1;v<=_V;v++)
            {
                if(G[u][v])
                {
                    if(ancestor[v]>deep[u])branch++;
                    if(ancestor[v]==deep[u])f=true;
                }
            }
            printf("  SPF node %d leaves %d subnets\n",u,branch+f);
        }
    }
    if(!exist)printf("  No SPF nodes\n");
    cout<<endl;
}
int main()
{
 //   freopen("data.in","r",stdin);
    int Case=1;
    int u,v;
    while(~scanf("%d",&u)&&u)
    {
        init();
        scanf("%d",&v);
        vis[u]=vis[v]=G[u][v]=G[v][u]=true;

        while(~scanf("%d",&u)&&u)
        {
            scanf("%d",&v);
            G[u][v]=G[v][u]=true;
            if(!vis[u])
            {
                vis[u]=true;
                _V++;
            }
            if(!vis[v])
            {
                vis[v]=true;
                _V++;
            }
        }

        dfs(1,0,0);

        output(Case);
        Case++;
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章