HDU3836 Equivalent Sets :Tarjan縮點

HDU3836 Equivalent Sets :Tarjan縮點

Description

一個N個點與M條邊的有向圖,求出需要加多少使其變爲一個強聯通分量.

Input

若干組測試數據.
每組數據第一行爲N,M
後面M行爲兩個正整數A,B,代表A到B有一條有向邊.

Output

對應每組數據輸出一個整數,及要加的最小邊數.

Sample Input

4 0
3 2
1 2
1 3

Sample Output

4
2

HINT

N <= 20000,M <= 50000

題解

可以先進行縮點.然後就有一個無環有向圖。
我們可以嘗試發現只有然所有連通塊的入度與出度不爲0就可以變成一個連通塊。
那麼就讓加的每一條邊從一個出度爲0的連通塊連接一個入度爲0的連通塊即可。
所以答案就算max(出度爲0的連通塊的個數,入度爲0的連通塊的個數)

#include <cstdio>
#include <iostream>
#include <cmath>
#include <stack>
#include <algorithm>
#include <cstring>
#include <climits>
#define MAXN 40000+10
#define MAXM 70000+10
using namespace std;

int head[MAXN],num,n,m;
int dfn[MAXN],low[MAXN],vis[MAXN],dfnum,col[MAXN],co;
int ru[MAXN],rans,cans,cu[MAXN],t;
stack<int> st;
struct Edge{
    int from,to,next;
}edge[MAXN<<1];
void add(int from,int to)
{
    edge[++num].next=head[from];
    edge[num].from=from;
    edge[num].to=to;
    head[from]=num;
}
void tarjian(int x)
{   
    dfn[x]=low[x]=++dfnum;
    vis[x]=1;st.push(x);
    for(int i=head[x];i;i=edge[i].next)
    {
        if(!dfn[edge[i].to])
        {
            tarjian(edge[i].to);
            low[x]=min(low[x],low[edge[i].to]);
        }else if(vis[edge[i].to]) low[x]=min(low[x],dfn[edge[i].to]);
    }
    if(dfn[x]==low[x])
    {
        col[x]=++co;
        vis[x]=0;
        while(st.top()!=x){col[st.top()]=co;vis[st.top()]=0;st.pop();}
        st.pop();
    }
}
int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        num=0;rans=cans=co=dfnum=0;
        memset(ru,0,sizeof(ru));
        memset(cu,0,sizeof(cu));
        memset(edge,0,sizeof(edge));
        memset(head,0,sizeof(head));
        memset(dfn,0,sizeof(dfn));
        memset(low,0,sizeof(low));
        memset(col,0,sizeof(col));
        memset(vis,0,sizeof(vis));
        while( !st.empty() )
      st.pop();

        for(int i=1;i<=m;i++)
        {   
            int x,y;
            scanf("%d%d",&x,&y);
            add(x,y);
        }
        for(int i=1;i<=n;i++)
        if(!col[i])
        tarjian(i);
        for(int i=1;i<=num;i++)
        {   
            if(col[edge[i].from]!=col[edge[i].to])
            ru[col[edge[i].to]]++,cu[col[edge[i].from]]++;
        }
        for(int i=1;i<=co;i++)
        {   
            if(ru[i]==0) rans++;
            if(cu[i]==0) cans++;
        }
        if(co!=1)
        printf("%d\n",max(rans,cans));
        else printf("0\n");
    }
    return 0;
}
發佈了50 篇原創文章 · 獲贊 4 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章