1061: [Noi2008]志愿者招募
Time Limit: 20 Sec Memory Limit: 162 MBSubmit: 3483 Solved: 2131
[ Submit][ Status][ Discuss]
Description
Input
Output
仅包含一个整数,表示你所设计的最优方案的总费用。
Sample Input
2 3 4
1 2 2
2 3 5
3 3 2
Sample Output
HINT
1 ≤ N ≤ 1000,1 ≤ M ≤ 10000,题目中其他所涉及的数据均 不超过2^31-1。
解题思路:https://www.byvoid.com/blog/noi-2008-employee/
线性规划的两种做法,网络流或单纯性
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int n,m,len,S,T,ans;
const int INF=0x7fffffff;
int from[40000],to[40000],next[40000],h[40000],f[40000],w[40000];
bool b[1010];
int dis[1010],q[10000000],pre[1010];
int a[1010];
inline int read()
{
char y; int x=0,f=1; y=getchar();
while (y<'0' || y>'9') {if (y=='-') f=-1; y=getchar();}
while (y>='0' && y<='9') {x=x*10+int(y)-48; y=getchar();}
return x*f;
}
void insert(int x,int y,int flow,int v)
{
++len; from[len]=x; to[len]=y; next[len]=h[x]; h[x]=len; f[len]=flow; w[len]=v;
}
bool spfa()
{
memset(b,true,sizeof(b)); b[S]=false;
memset(dis,0x7f,sizeof(dis)); dis[S]=0;
int tail=1,head=0; q[tail]=S;
while (head<tail)
{
++head;
int u=h[q[head]];
while (u!=0)
{
if (f[u]>0 && dis[to[u]]>dis[q[head]]+w[u])
{
dis[to[u]]=dis[q[head]]+w[u];
pre[to[u]]=u;
if (b[to[u]])
{
b[to[u]]=false;
++tail; q[tail]=to[u];
}
}
u=next[u];
}
b[q[head]]=true;
}
if (dis[T]<10000000) return true;else return false;
}
void mcf()
{
int now=T; int mx=0x7fffffff;
while (now!=S)
{
mx=min(mx,f[pre[now]]);
now=from[pre[now]];
}
now=T;
while (now!=S)
{
ans+=mx*w[pre[now]];
f[pre[now]]-=mx; f[pre[now]^1]+=mx;
now=from[pre[now]];
}
}
int main()
{
n=read(); m=read(); len=1; S=0; T=n+2;
for (int i=1;i<=n;++i)
{
a[i]=read();
int u=a[i]-a[i-1];
if (u>0)
{
insert(S,i,u,0); insert(i,S,0,0);
}else
{
insert(i,T,-u,0); insert(T,i,0,0);
}
insert(i+1,i,INF,0);insert(i,i+1,0,0);
}
insert(n+1,T,a[n],0); insert(T,n+1,0,0);
insert(n+1,n,INF,0); insert(n,n+1,0,0);
for (int i=1;i<=m;++i)
{
int s,t,c; s=read(); t=read(); c=read();
insert(s,t+1,INF,c); insert(t+1,s,0,-c);
}
ans=0;
while (spfa())
{
mcf();
}
printf("%d",ans);
}