bzoj1927: [Sdoi2010]星际竞速

求一个DAG图的带权最小不相交路径覆盖

不带权的话就是二分图匹配了

带权我是真的不会。KM应该可行?不。对于不带权,我找到一个匹配点,相当于减少了需要的链数,然而这里找到一个匹配点并不能保证更优秀,因为传送并不一定比开过去更优。

而匈牙利和网络流是等价的,那么考虑使用费用流

拆点,分成入点和出点,st连向出点费用为传送的费用,st连入点为0

出点连ed费用为0,边的x的出点连向y的入点费用为边权

流量均为1

和不带权类似的理解方式,费用的边权形成了二分图中的增广路,这条增广路只是一条路径所以流量只能为1,而这些st连入点为0补充了增广路其他点的流量

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<map>
using namespace std;
typedef long long LL;

struct node
{
    int x,y,c,d,next;
}a[310000];int len,last[21000];
void ins(int x,int y,int c,int d)
{
    len++;
    a[len].x=x;a[len].y=y;a[len].c=c;a[len].d=d;
    a[len].next=last[x];last[x]=len;
    
    len++;
    a[len].x=y;a[len].y=x;a[len].c=0;a[len].d=-d;
    a[len].next=last[y];last[y]=len;
}

int st,ed;
int pre[21000],c[21000];LL ans,d[21000];
int list[21000];bool v[21000];
bool spfa()
{
    memset(d,63,sizeof(d));d[st]=0;c[st]=(1<<30);
    memset(v,false,sizeof(v));v[st]=true;
    int head=1,tail=2;list[1]=st;
    while(head!=tail)
    {
        int x=list[head];
        for(int k=last[x];k;k=a[k].next)
        {
            int y=a[k].y;
            if(a[k].c>0&&d[y]>d[x]+a[k].d)
            {
                d[y]=d[x]+a[k].d;
                c[y]=min(a[k].c,c[x]);
                pre[y]=k;
                if(v[y]==false)
                {
                    v[y]=true;
                    list[tail]=y;
                    tail++;if(tail==20100)tail=1;
                }
            }
        }
        v[x]=false;
        head++;if(head==20100)head=1;
    }
    if(d[ed]==d[0])return false;
    else
    {
        int y=ed;ans+=c[ed]*d[ed];
        while(y!=st)
        {
            int k=pre[y];
            a[k].c-=c[ed];
            a[k^1].c+=c[ed];
            y=a[k].x;
        }
        return true;
    }
}
int main()
{
    freopen("a.in","r",stdin);
    freopen("a.out","w",stdout);
    int n,m,x,y,dd;
    scanf("%d%d",&n,&m);st=2*n+1,ed=2*n+2;
    len=1;memset(last,0,sizeof(last));
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&dd);
        ins(st,i,1,0);
        ins(st,i+n,1,dd);
        ins(i+n,ed,1,0);
    }
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&x,&y,&dd);
        if(x>y)swap(x,y);
        ins(x,y+n,1,dd);
    }
    while(spfa());
    printf("%lld
",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/AKCqhzdy/p/9884196.html