# Permutation【省选模拟赛】

## 网络流思维好题

Posted by yjjr's blog on March 30, 2018

n<=500，m<=1000。

# code

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#define mem(x,num) memset(x,num,sizeof x)
#define reg(x) for(int i=last[x];i;i=e[i].next)
using namespace std;
ll f=1,x=0;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
#define inf 1e9
const int maxn=1e4+6;
struct edge{int to,next,v;}e[maxn<<2];
int S,T,n,m,cnt=1,a[maxn],h[maxn],u[maxn],v[maxn],last[maxn],que[maxn<<2];
ll ans=0;
void insert(int u,int v,int w){
e[++cnt]=(edge){v,last[u],w};last[u]=cnt;
e[++cnt]=(edge){u,last[v],0};last[v]=cnt;
}
inline bool bfs(){
mem(h,-1);que[0]=S,h[S]=0;
reg(now)
if(e[i].v&&h[e[i].to]==-1){h[e[i].to]=h[now]+1;que[tail++]=e[i].to;}
}
return h[T]!=-1;
}
inline int dfs(int x,int f){
if(x==T)return f;
int w,used=0;
reg(x)
if(e[i].v&&h[e[i].to]==h[x]+1){
w=dfs(e[i].to,min(f-used,e[i].v));
e[i].v-=w;e[i^1].v+=w;
used+=w;if(used==f)return f;
}
if(!used)h[x]=-1;
return used;
}
void dinic(){while(bfs())ans-=dfs(S,inf);}
int main()
{
freopen("permutation.in","r",stdin);
freopen("permutation.out","w",stdout);
rep(i,1,n){
if(x>0){
ans+=x;
insert(S,2*i+1,x);
insert(2*i+2,T,x);
}else insert(2*i+1,2*i+2,-x);
}
rep(i,1,m){