UVA10480 Sabotage (Dinic版最小割边集)

读题

给定n和m,n表示点的数量,m表示边的数量。
再给m条边(u,v,w)。w表示割点该边的花费。注意是无向图,反向边的容量与正向边一致。将结点1看作源点,结点2看作汇点,求一组最小割边集。

解题

最小割等于最大流。如果“一条边满流”和“去掉该边后网络的最大流减小的量等于该边的容量”两个条件同时满足,那么该边就是最小割边集的一条边。
故在跑一遍dinic算法后,在残量网络中,将源点S能到达的点看作S集,其他点看作T集。如果边的一个点属于S集,另一个点属于T集,那么该边属于最小割边集。

AC代码

//跑一遍dinic算法后,
//在残量网络中,从源点出发能到达的点看作S集
//剩下的看作T集,若一条边(u,v),u属于S集,v属于T集。
//那么该边就是最小割边集的边
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
#include <string>
#define INF 0x3f3f3f3f
using namespace std;

int S,T;//源点和汇点
const int maxe=1e5+1000;
const int maxv=1100;
struct edge
{
    int to,w,next;
}e[maxe<<1];
int head[maxv<<1],depth[maxv],cnt;
void init()
{
    memset(head,-1,sizeof(head));
    cnt=-1;
}
void add_edge(int u,int v,int w)
{
    e[++cnt].to=v;
    e[cnt].w=w;
    e[cnt].next=head[u];
    head[u]=cnt;
}
void _add(int u,int v,int w)
{
    add_edge(u,v,w);
    add_edge(v,u,w);
}

bool bfs()
{
    queue<int> q;
    while(!q.empty()) q.pop();
    memset(depth,0,sizeof(depth));
    depth[S]=1;
    q.push(S);

    while(!q.empty())
    {
        int u=q.front();q.pop();
        for(int i=head[u];i!=-1;i=e[i].next)
        {
            if(!depth[e[i].to] && e[i].w>0)
            {
                depth[e[i].to]=depth[u]+1;
                q.push(e[i].to);
            }
        }
    }
    if(!depth[T]) return false;
    return true;
}
int dfs(int u,int flow)
{
    if(u==T) return flow;
    int ret=0;
    for(int i=head[u];i!=-1 && flow;i=e[i].next)
    {
        if(depth[u]+1==depth[e[i].to] && e[i].w!=0)
        {
            int tmp=dfs(e[i].to,min(e[i].w,flow));
            if(tmp>0)
            {
                flow-=tmp;
                ret+=tmp;
                e[i].w-=tmp;
                e[i^1].w+=tmp;
            }
        }
    }
    return ret;
}
int Dinic()
{
    int ans=0;
    while(bfs())
    {
        ans+=dfs(S,INF);
    }
    return ans;
}
struct Gedge
{
    int u,v;
}a[550];//图的边集
int tot,vis[55];
void DFS(int u)
{
    vis[u]=1;//为1表示是S集的点
    for(int i=head[u];i!=-1;i=e[i].next)
    {
        int v=e[i].to;
        if(vis[v] || e[i].w<=0) continue;
        DFS(v);
    }
}
int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        if(n==0 && m==0) break;
        init();
        tot=0;
        S=1,T=2;
        while(m--)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);//给的是一个无向图
            _add(u,v,w);//注意反向边容量和正向边容量一致
            a[tot].u=u,a[tot++].v=v;
        }
        Dinic();
        memset(vis,0,sizeof(vis));
        DFS(S);//确定S集和T集
        for(int i=0;i<tot;i++)
        {
            int u=a[i].u,v=a[i].v;
            if(vis[u]&&!vis[v] || vis[v]&&!vis[u])
                printf("%d %d\n",u,v);
        }
        putchar(10);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37685156/article/details/80633097