首先可以对于一条非树边(x,y,len1),对应的树上x~y的链中的某一条边(u,v,len2),如果有len1<len2,那么显然需要让len1加上一个值a,len2减去一个值b,满足a+b>=len2-len1。
显然一条非树边对应一个a,一条树边对应一个b,然后a+b>=len2-len1相当于最大权匹配中的顶标号。那么建一个二分图跑最大匹配即最大费用流(不需要满流)。
AC代码如下:
#include<iostream> #include<cstdio> #include<cstring> #define N 1005 #define M 100005 using namespace std; int n,m,tot=1,gol,a[55][55],pnt[M],nxt[M],edg[M],len[M],fa[N],d[N],h[M+5]; bool bo[N]; struct graph{ int fst[N]; void add(int x,int y,int z,int w){ pnt[++tot]=y; len[tot]=z; edg[tot]=w; nxt[tot]=fst[x]; fst[x]=tot; } }g1,g2; void dfs(int x,int last){ int p; for (p=g1.fst[x]; p; p=nxt[p]){ int y=pnt[p]; if (y!=last){ fa[y]=p; dfs(y,x); } } } bool spfa(){ memset(d,192,sizeof(d)); d[0]=0; memset(bo,1,sizeof(bo)); int head=0,tail=1; h[1]=0; while (head!=tail){ head=head%M+1; int x=h[head],p; bo[x]=1; for (p=g2.fst[x]; p; p=nxt[p]) if (len[p]){ int y=pnt[p]; if (d[x]+edg[p]>d[y]){ d[y]=d[x]+edg[p]; fa[y]=p; if (bo[y]){ tail=tail%M+1; h[tail]=y; bo[y]=0;} } } } return d[gol]>0; } int up(){ int i,tmp=1000000000,sum=0; for (i=gol; i; i=pnt[fa[i]^1]) tmp=min(tmp,len[fa[i]]); for (i=gol; i; i=pnt[fa[i]^1]){ sum+=tmp*edg[fa[i]]; len[fa[i]]-=tmp; len[fa[i]^1]+=tmp; } return sum; } int main(){ scanf("%d%d",&n,&m); int i,j,x,y; for (i=1; i<=m; i++){ scanf("%d%d",&x,&y); scanf("%d",&a[x][y]); a[y][x]=a[x][y]; } for (i=1; i<n; i++){ scanf("%d%d",&x,&y); g1.add(x,y,a[x][y],i); g1.add(y,x,a[y][x],i); a[x][y]=a[y][x]=0; } gol=n; for (i=1; i<n; i++) for (j=i+1; j<=n; j++) if (a[i][j]){ dfs(i,0); for (x=j; x!=i; x=pnt[fa[x]^1]){ y=edg[fa[x]]; if (a[i][j]<len[fa[x]]){ g2.add(y,gol,1,len[fa[x]]-a[i][j]); g2.add(gol,y,0,a[i][j]-len[fa[x]]); } } gol++; } for (i=1; i<n; i++){ g2.add(0,i,1,0); g2.add(i,0,0,0); } for (i=n; i<gol; i++){ g2.add(i,gol,1,0); g2.add(gol,i,0,0); } int ans=0; while (spfa()) ans+=up(); printf("%d\n",ans); return 0; }
by lych
2016.4.12