题解

1 条题解

  • 0
    @ 2017-08-25 19:09:06

    -----------------------------------------------AC code-----------------------------------------------

    #include<algorithm>
    #include<cstdio>
    #include<stack>
    
    using namespace std;
    
    const int MAXN = 100005;
    const int MAXM = 500005;
    
    int n, m, u[MAXM], v[MAXM];
    int sum_ind, sum_outd;
    
    struct Edge{
        int nxt, to;
    }edge[MAXM], e[MAXM];
    
    int head[MAXN], edge_num;
    void add_edge(int from, int to){
        edge[++edge_num].nxt = head[from];
        edge[edge_num].to = to;
        head[from] = edge_num;
    }
    
    int hd[MAXN], e_n, ind[MAXN], outd[MAXN];
    void a_e(int from, int to){
        e[++e_n].nxt = hd[from];
        e[e_n].to = to;
        hd[from] = e_n;
        ind[to]++;
        outd[from]++;
    }
    
    int dfn[MAXN], low[MAXN], scc, belong[MAXN], dex;
    stack<int> s;
    bool ins[MAXN];
    void tarjan(int x){
        dfn[x] = low[x] = ++dex;
        s.push(x);
        ins[x] = 1;
        for(int i = head[x]; i; i = edge[i].nxt){
            if(!dfn[edge[i].to]){
                tarjan(edge[i].to);
                dfn[x] = min(dfn[edge[i].to], dfn[x]);
            }
            else
                if(ins[edge[i].to])
                    dfn[x] = min(dfn[x], low[edge[i].to]);
        }
        if(dfn[x] == low[x]){
            scc++;
            while(1){
                int cur = s.top(); s.pop(); ins[cur] = 0;
                belong[cur] = scc;
                if(cur == x)    break;
            }
        }
    }
    
    int main(){
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= m; i++){
            scanf("%d%d", &u[i], &v[i]);
            add_edge(u[i], v[i]);
        }
        for(int i = 1; i <= n; i++)
            if(!dfn[i])
                tarjan(i);
        for(int i = 1; i <= m; i++)
            if(belong[u[i]] != belong[v[i]])
                a_e(belong[u[i]], belong[v[i]]);
        if(scc == 1){
            putchar('0');
            return 0;
        }
        for(int i = 1; i <= scc; i++){
            if(ind[i] == 0) sum_ind++;
            if(outd[i] == 0)    sum_outd++;
        }
        printf("%d", max(sum_ind, sum_outd));
        return 0;
    }
    
  • 1

信息

难度
(无)
分类
强连通分量图结构 点击显示
标签
递交数
0
已通过
0
通过率
?
上传者