首页 > 代码库 > HDU 4738 无向图求桥

HDU 4738 无向图求桥

使用tarjan算法求桥,模板题,但是。。。

1.有重边

2.不一定连通

3.没有人守桥至少要派一个人去

http://acm.hdu.edu.cn/showproblem.php?pid=4738

这种题挺好的,可以锻炼人的耐性和心理承受能力。。。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
using namespace std;
const int N = 1000 + 5;
const int INF = 0x3f3f3f3f;
int n,m;
int dfs_clock, pre[N], low[N];

struct Edge
{
    int u,v,w;
    int iscut;
    Edge() {}
    Edge(int a, int b, int c, int d):u(a), v(b), w(c), iscut(d) {}
};
vector<Edge> edges;
vector<int> G[N];
void addedge(int u, int v, int w)
{
    edges.push_back(Edge(u, v, w, 0));
    edges.push_back(Edge(v, u, w, 0));
    int m = edges.size();
    G[u].push_back(m-2);
    G[v].push_back(m-1);
}
void init()
{
    edges.clear();
    for(int i = 0; i <= 1000; i++)
        G[i].clear();
    memset(pre, 0, sizeof(pre));
    memset(low, 0, sizeof(low));
    dfs_clock = 0;
}
int tarjan(int u, int fa)
{
    int lowu = pre[u] = ++dfs_clock;
    int flag = 1;
    for(int i = 0; i < G[u].size(); i++)
    {
        Edge &e = edges[G[u][i]];
        int v = e.v,lowv;
        if(flag && v == fa)
        {
            flag = 0;
            continue;
        }
        if(!pre[v])
        {
            lowv = tarjan(v, u);
            lowu = min(lowu, lowv);
            if(lowv > pre[u])
            {
                e.iscut = 1;
                edges[G[u][i]^1].iscut = 1;
            }
        }
        else
        {
            lowu = min(lowu, pre[v]);
        }
    }
    low[u] = lowu;
    return lowu;
}

int main()
{
    while(scanf("%d%d", &n, &m),n||m)
    {
        init();
        for(int i = 0; i < m; i++)
        {
            int u,v,w;
            scanf("%d%d%d", &u,&v,&w);
            addedge(u,v,w);
        }
        tarjan(edges[0].u, -1);
        int flag = 0;
        for(int i = 1; i <= n; i++)
            if(pre[i] == 0)
            {
                flag = 1;
                break;
            }
        if(flag)
        {
            printf("0\n");
            continue;
        }
        int ans = INF;
        for(int i = 0; i < edges.size(); i++)
        {
            if(edges[i].iscut)
            {
                ans = min(ans, edges[i].w);
            }
        }
        if(ans == INF)
            printf("-1\n");
        else
            printf("%d\n", ans == 0 ? 1 : ans);
    }
}

 

HDU 4738 无向图求桥