Light OJ 1034 - Hit the Light Switches(強聯通分量)

來源:互聯網
上載者:User

標籤:int   min   bool   強聯通   its   聯通   c++   namespace   div   

題目連結:http://www.lightoj.com/volume_showproblem.php?problem=1034

題目大意:有n盞燈,有m個關係, 關係a,b表示如果a燈開關開啟那麼b燈也會亮起來, 現在求至少需要開啟多少開關使所有燈都亮。

題目思路:先由強聯通分量縮點, 得到DAG圖, 然後根據DAG圖,求出有多少入度為0的點, 即為所求。

代碼如下:

#include<bits/stdc++.h>using namespace std;const int N = 10007;vector<int>vec[N], stk;int low[N], dfn[N], belong[N], in[N];bool mk[N];int tot, cou_scc;void tarjan(int u, int f){    dfn[u] = low[u]= tot ++;    stk.push_back(u), mk[u] = true;    for(int i=0; i<vec[u].size(); ++ i)    {        int v = vec[u][i];        if(dfn[v] == -1)        {            tarjan(v, u);            low[u] = min(low[u], low[v]);        }        else if(mk[v])        {            low[u] = min(low[u], dfn[v]);        }    }    if(low[u] == dfn[u])    {        ++ cou_scc;        while(1)        {            int v = stk.back();            stk.pop_back();            mk[v] = false;            belong[v] = cou_scc;            if(u == v)                break;        }    }}void solve(int cases){    int n, m;    scanf("%d%d", &n, &m);    for(int i=1; i<=n; ++ i)        vec[i].clear();    int u, v;    for(int i=1; i<=m; ++ i)    {        scanf("%d%d", &u, &v);        vec[u].push_back(v);    }    memset(low, -1, sizeof(low));    memset(dfn, -1, sizeof(dfn));    memset(mk, false, sizeof(mk));    tot = 0, cou_scc = 0;    for(int i=1; i<=n; ++ i)    {        if(dfn[i] == -1)            tarjan(i, -1);    }    memset(in, 0, sizeof(in));    for(int i=1; i<=n; ++ i)    {        for(int j=0; j<vec[i].size(); ++ j)        {            int v = vec[i][j];            if(belong[i] != belong[v])                in[belong[v]] ++;        }    }    int ans = 0;    for(int i=1; i<=cou_scc; ++ i)    {        if(in[i] == 0)            ans ++;    }    printf("Case %d: %d\n", cases, ans);}int main(){    int t;    scanf("%d", &t);    for(int i=1; i<=t; ++ i)        solve(i);    return 0;}

 

Light OJ 1034 - Hit the Light Switches(強聯通分量)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.