首页 > 代码库 > BZOJ 2424 订货

BZOJ 2424 订货

费用流。

#include<iostream>#include<cstdio>#include<queue>#include<cstring>#include<algorithm>#define maxv 250#define maxe 1000050#define inf 2000000000using namespace std;int n,m,S,u[maxv],d[maxv],nume=1,g[maxv],dis[maxv],pree[maxv],prev[maxv],s,t;queue <int> q;bool vis[maxv];struct edge{    int v,f,c,nxt;}e[maxe];void addedge(int u,int v,int f,int c){    e[++nume].v=v;e[nume].f=f;e[nume].c=c;e[nume].nxt=g[u];g[u]=nume;    e[++nume].v=u;e[nume].f=0;e[nume].c=-c;e[nume].nxt=g[v];g[v]=nume;}void build(){    s=0;t=2*n+1;    for (int i=1;i<=n;i++)    {        addedge(s,i,inf,d[i]);        addedge(i,i+n,inf,0);        addedge(i+n,t,u[i],0);    }    for (int i=1;i<=n-1;i++)        addedge(i+n,i+1,S,m);}bool spfa(){    for (int i=s;i<=t;i++) {pree[i]=prev[i]=-1;dis[i]=inf;vis[i]=false;}    q.push(s);vis[s]=true;dis[s]=0;    while (!q.empty())    {        int head=q.front();q.pop();        for (int i=g[head];i;i=e[i].nxt)        {            int v=e[i].v;            if ((e[i].f) && (dis[v]>dis[head]+e[i].c))            {                dis[v]=dis[head]+e[i].c;                pree[v]=i;prev[v]=head;                if (!vis[v]) {q.push(v);vis[v]=true;}            }        }        vis[head]=false;    }    if (dis[t]==inf) return false;    return true;}int dinic(){    int u=t,low=inf;    while (u!=s)    {        low=min(low,e[pree[u]].f);        u=prev[u];    }    u=t;    while (u!=s)    {        e[pree[u]].f-=low;e[pree[u]^1].f+=low;        u=prev[u];    }    return dis[t]*low;}int main(){    scanf("%d%d%d",&n,&m,&S);    for (int i=1;i<=n;i++) scanf("%d",&u[i]);    for (int i=1;i<=n;i++) scanf("%d",&d[i]);    build();    int min_cost=0;    while (spfa()) min_cost+=dinic();    printf("%d\n",min_cost);    return 0;}

 

BZOJ 2424 订货