1. 程式人生 > >bzoj 1927 [Sdoi2010]星際競速【最小費用最大流】

bzoj 1927 [Sdoi2010]星際競速【最小費用最大流】

流量 source 覆蓋 tdi png code struct || 就是

果然還是不會建圖…
設\( i \)到\( j \)有通路,代價為\( w[i][j] \),瞬移到i代價為\( a[i] \),瞬移到i代價為\( a[j] \),逗號前是流量。
技術分享圖片
因為每個點只能經過一次,所以流量限制為1,註意到從s開始很難保證出發點不同,所以但是又有聯通條件,所以考慮每個擴展過的點(實際不用考慮反正早晚要擴展到)只向外擴展一個點,也就是每次只選兩個聯通的點(包括瞬移可達)
拆點的作用是加上費用,\( s \)到所有\( i \)連流量1費用0的邊,所有\(i \)向t連流量1費用0的邊,\( i \)到\( i+n \)連流量1費用\( a[i] \)的邊,對於可以相互到達的\( i、j \),連流量為1費用為\( v[i][j] \)的邊(\( u<v \))

是不是有點像最小路徑覆蓋?

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int N=5005,inf=1e9;
int n,m,a[N],s,t,ans,fr[N],dis[N],h[N],cnt=1;
bool v[N];
struct qwe
{
    int ne,no,to,va,c;
}e[N*100];
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>‘9‘
||p<‘0‘) { if(p==‘-‘) f=-1; p=getchar(); } while(p>=‘0‘&&p<=‘9‘) { r=r*10+p-48; p=getchar(); } return r*f; } void add(int u,int v,int w,int c) { cnt++; e[cnt].ne=h[u]; e[cnt].no=u; e[cnt].to=v; e[cnt].va=w; e[cnt].c=c; h[u]=cnt; } void
ins(int u,int v,int w,int c) { add(u,v,w,c); add(v,u,0,-c); } bool spfa() { queue<int>q; for(int i=s;i<=t;i++) dis[i]=inf; dis[s]=0; v[s]=1; q.push(s); while(!q.empty()) { int u=q.front(); q.pop(); v[u]=0; for(int i=h[u];i;i=e[i].ne) if(e[i].va>0&&dis[e[i].to]>dis[u]+e[i].c) { dis[e[i].to]=dis[u]+e[i].c; fr[e[i].to]=i; if(!v[e[i].to]) { v[e[i].to]=1; q.push(e[i].to); } } } return dis[t]!=inf; } void mcf() { int x=inf; for(int i=fr[t];i;i=fr[e[i].no]) x=min(x,e[i].va); for(int i=fr[t];i;i=fr[e[i].no]) { ans+=x*e[i].c; e[i].va-=x; e[i^1].va+=x; } } int main() { n=read(),m=read(); t=2*n+1; for(int i=1;i<=n;i++) { a[i]=read(); ins(s,i,1,0); ins(i+n,t,1,0); ins(s,i+n,1,a[i]); } for(int i=1;i<=m;i++) { int u=read(),v=read(),w=read(); if(u>v) swap(u,v); ins(u,v+n,1,w); } while(spfa()) mcf(); printf("%d\n",ans); return 0; }

bzoj 1927 [Sdoi2010]星際競速【最小費用最大流】