spoj 371

最小费用流水之

#include<cstdio>
#include<cstring>
#include<queue>
#define N 1010
#define inf 100000000
using namespace std;
int n,cnt;
int head[N],pre[N],vis[N];
int dis[N];
int ans;
struct Edge{
    int u,v,c,next;
    int w;
}edge[8010];
void init(){
    memset(head,-1,sizeof(head));
    cnt=ans=0;
}
void addedge(int u,int v,int cap,int cost){
    edge[cnt].u=u;
    edge[cnt].v=v;
    edge[cnt].c=cap;
    edge[cnt].w=cost;
    edge[cnt].next=head[u];
    head[u]=cnt++;
    edge[cnt].u=v;
    edge[cnt].v=u;
    edge[cnt].c=0;
    edge[cnt].w=-cost;
    edge[cnt].next=head[v];
    head[v]=cnt++;
}
bool spfa(){
    int i,j;
    queue<int>q;
    q.push(0);
    for(i=1;i<=n;i++){
        dis[i]=inf;
        vis[i]=0;
    }
    dis[0]=0,vis[0]=1;
    while(!q.empty()){
        int u=q.front();
        q.pop();
        vis[u]=0;
        for(i=head[u];i!=-1;i=edge[i].next){
            int v=edge[i].v;
            if(edge[i].c && dis[v] > dis[u]+edge[i].w){
                dis[v]=dis[u]+edge[i].w;
                pre[v]=i;
                if(!vis[v]){
                    vis[v]=1;
                    q.push(v);
                }
            }
        }
    }
    if(dis[n]==inf)return 0;
    return 1;
}
void end(){
    int u,p,cap=-1;
    for(u=n;u;u=edge[p].u){
        p=pre[u];
        if(cap==-1 || cap>edge[p].c)
            cap=edge[p].c;
    }
    for(u=n;u;u=edge[p].u){
        p=pre[u];
        edge[p].c-=cap;
        edge[p^1].c+=cap;
        ans+=cap*edge[p].w;
    }
}
int cal(int u){
    if(u==0)return n-1;
    if(u==n)return 1;
    return u;
}
int main(){
    int t,T,i;
    int v,tem;
    scanf("%d",&T);
    for(t=1;t<=T;t++){
        init();
        scanf("%d",&v);
        n=v+1;
        for(i=1;i<=v;i++){
            scanf("%d",&tem);
            if(tem)
                addedge(0,i,tem,0);
            addedge(i,n,1,0);
            addedge(i,cal(i+1),inf,1);
            addedge(i,cal(i-1),inf,1);
        }
        while(spfa())
            end();
        printf("%d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(spoj 371)