演算法:poj 1523 SPF(tarjan求割點)

來源:互聯網
上載者:User

題意

給一個連通的無向圖,求這個圖的所有割點,並且輸出各個割點和相連的邊去掉之後,會變成幾 個連通分量

思路

用tarjan求割點的基礎題,要求對tarjan演算法的原理真正搞懂,這題就水了。

代碼

/**=====================================================* This is a solution for ACM/ICPC problem** @source : poj-1523 SPF* @description : 圖的連通性-tarjan求割點* @author : shuangde* @blog : blog.csdn.net/shuangde800* @email : zengshuangde@gmail.com* Copyright (C) 2013/09/04 20:15 All rights reserved.*======================================================*/#include <iostream>#include <cstdio>#include <algorithm>#include <vector>#include <cmath>#include <cstring>using namespace std;    typedef long long int64;const int INF = 0x3f3f3f3f;    const int MAXN = 1010;int n;bool ok;int cnt[MAXN];    namespace Adj {int size, head[MAXN];struct Node {int v, next;}E[MAXN*2];inline void initAdj() {size = 0;memset(head, -1, sizeof(head));}inline void addEdge (int u, int v) {E[size].v = v;E[size].next = head[u];head[u] = size++;}}using namespace Adj;        namespace Tarjan {bool vis[MAXN];int dfn[MAXN], low[MAXN], idx;    inline void initTarjan() {idx = 1;memset(vis, 0, sizeof(vis));memset(dfn, 0, sizeof(dfn));memset(low, 0, sizeof(low));}    void tarjan(int u) {    vis[u] = true;dfn[u] = low[u] = idx++;// http://www.bianceng.cn    for (int e = head[u]; e != -1; e = E[e].next) {int v = E[e].v;if (vis[v]) {low[u] = min(low[u], dfn[v]);} else {tarjan(v);low[u] = min(low[u], low[v]);if (u == 1) {++cnt[u];if (cnt[u] == 2) ok = true;}else if (low[v] >= dfn[u]) {ok = true;++cnt[u];}}}}}using namespace Tarjan;    int main(){    int cas = 1;int u, v;while (~scanf("%d", &u) && u) {    scanf("%d", &v);initAdj();n = 0;n = max(n, max(u, v));addEdge(u, v);addEdge(v, u);    while (~scanf("%d", &u) && u) {scanf("%d", &v);n = max(n, max(u, v));addEdge(u, v);addEdge(v, u);}    if (cas != 1) puts("");printf("Network #%d\n", cas++);    memset(cnt, 0, sizeof(cnt));ok = false;initTarjan();tarjan(1);    if (!ok) puts(" No SPF nodes");else {if (cnt[1] > 1)printf(" SPF node %d leaves %d subnets\n", 1, cnt[1]);for (int i = 2; i <= n; ++i) {if (cnt[i])printf(" SPF node %d leaves %d subnets\n", i, cnt[i] + 1);}}}    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.