POJ_2455

    每条路只走一次可以通过网络流来保证,而对于让最长的边最小可以通过二分枚举来搞定。

#include<stdio.h>
#include<string.h>
#include<algorithm>
#define MAXD 210
#define MAXM 80010
#define INF 0x3f3f3f3f
int N, M, P, first[MAXD], e, next[MAXM], v[MAXM], flow[MAXM], MID;
int S, T, d[MAXD], q[MAXD], work[MAXD], tx[MAXM];
struct Edge
{
    int x, y, z;
}edge[MAXM];
void add(int x, int y, int z)
{
    v[e] = y, flow[e] = z;
    next[e] = first[x], first[x] = e ++;    
}
void init()
{
    int i;
    for(i = 0; i < M; i ++)
        scanf("%d%d%d", &edge[i].x, &edge[i].y, &edge[i].z), tx[i] = edge[i].z;
    std::sort(tx, tx + M);
}
int bfs()
{
    int i, j, rear = 0;
    memset(d, -1, sizeof(d[0]) * (N + 1));
    d[S] = 0, q[rear ++] = S;
    for(i = 0; i < rear; i ++)
        for(j = first[q[i]]; j != -1; j = next[j])
            if(flow[j] && d[v[j]] == -1)
            {
                d[v[j]] = d[q[i]] + 1, q[rear ++] = v[j];
                if(v[j] == T) return 1;    
            }
    return 0;
}
int dfs(int cur, int a)
{
    if(cur == T) return a;
    for(int &i = work[cur]; i != -1; i = next[i])
        if(flow[i] && d[v[i]] == d[cur] + 1)
            if(int t = dfs(v[i], std::min(a, flow[i])))
            {
                flow[i] -= t, flow[i ^ 1] += t;
                return t;    
            }
    return 0;
}
int dinic()
{
    int ans = 0, t;
    while(bfs())
    {
        memcpy(work, first, sizeof(first[0]) * (N + 1));
        while(t = dfs(S, INF))
            ans += t;
    }
    return ans;
}
void build()
{
    int i;
    S = 1, T = N;
    memset(first, -1, sizeof(first[0]) * (N + 1)), e = 0;
    for(i = 0; i < M; i ++)
        if(edge[i].z <= MID)
            add(edge[i].x, edge[i].y, 1), add(edge[i].y, edge[i].x, 1);    
}
void solve()
{
    int i, ans = 0, min = -1, max = M - 1, mid;
    for(;;)
    {
        mid = (min + max + 1) >> 1;
        MID = tx[mid];
        if(mid == max) break;
        build();
        if(dinic() >= P)
            max = mid;
        else
            min = mid;
    }
    printf("%d\n", MID);
}
int main()
{
    while(scanf("%d%d%d", &N, &M, &P) == 3)
    {
        init();
        solve();    
    }
    return 0;    
}
posted on 2012-08-16 18:48  Staginner  阅读(197)  评论(0编辑  收藏  举报