bzoj3996: [TJOI2015]线性代数

看到这题想着大力画柿子

画完以后就是Σ(i=1~n)Σ(j=1~n) ai*aj*bij-Σai*ci

一个最大权闭合图的模型

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;

struct node
{
    int x,y,c,next,other;
}a[6100000];int len,last[310000];
void ins(int x,int y,int c)
{
    int k1,k2;
    
    len++;k1=len;
    a[len].x=x;a[len].y=y;a[len].c=c;
    a[len].next=last[x];last[x]=len;
    
    len++;k2=len;
    a[len].x=y;a[len].y=x;a[len].c=0;
    a[len].next=last[y];last[y]=len;
    
    a[k1].other=k2;
    a[k2].other=k1;
}
int st,ed,h[310000],list[310000];
bool bt_h()
{
    memset(h,0,sizeof(h));h[st]=1;
    int head=1,tail=2;list[1]=st;
    while(head!=tail)
    {
        int x=list[head];
        for(int k=last[x];k;k=a[k].next)
        {
            int y=a[k].y;
            if(a[k].c>0&&h[y]==0)
            {
                h[y]=h[x]+1;
                list[tail]=y;
                tail++;
            }
        }
        head++;
    }
    if(h[ed]==0)return false;
    return true;
}
int findflow(int x,int f)
{
    if(x==ed)return f;
    int s=0;
    for(int k=last[x];k;k=a[k].next)
    {
        int y=a[k].y;
        if(a[k].c>0&&h[y]==h[x]+1&&s<f)
        {
            int t=findflow(y,min(a[k].c,f-s));
            s+=t;a[k].c-=t;a[a[k].other].c+=t;
        }
    }
    if(s==0)h[x]=0;
    return s;
}

int b[510][510],c[510];
int main()
{
    freopen("a.in","r",stdin);
    freopen("a.out","w",stdout);
    
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            scanf("%d",&b[i][j]);
    for(int i=1;i<=n;i++)scanf("%d",&c[i]);
    
    st=n*n+n+1,ed=n*n+n+2;int sum=0;
    len=0;memset(last,0,sizeof(last));
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            ins(st,(i-1)*n+j,b[i][j]), sum+=b[i][j];
    for(int i=1;i<=n;i++)ins(n*n+i,ed,c[i]);
    
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            ins((i-1)*n+j,n*n+i,b[i][j]),
            ins((i-1)*n+j,n*n+j,b[i][j]);
    
    int ans=0;
    while(bt_h()==true)
    {
        ans+=findflow(st,(1<<30));
    }
    printf("%d\n",sum-ans);
    
    return 0;
}

 

posted @ 2018-09-13 22:05  AKCqhzdy  阅读(94)  评论(0编辑  收藏  举报