二分图棋盘模型,行列连边,求出最大独立集
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
inline int rd(){
int ret=0,f=1;char c;
while(c=getchar(),!isdigit(c))f=c=='-'?-1:1;
while(isdigit(c))ret=ret*10+c-'0',c=getchar();
return ret*f;
}
#define space() putchar(' ')
#define nextline() putchar('
')
void pot(int x){if(!x)return;pot(x/10);putchar('0'+x%10);}
void out(int x){if(!x)putchar('0');if(x<0)putchar('-'),x=-x;pot(x);}
const int MAXN = 2005;
const int INF = 1<<30;
int n,m;
int nex[MAXN*MAXN],to[MAXN*MAXN],fl[MAXN*MAXN];
int head[MAXN],ecnt=1;
inline void adds(int x,int y,int f){
nex[++ecnt]=head[x];to[ecnt]=y;
fl[ecnt]=f;head[x]=ecnt;
}
inline void add(int x,int y,int f){
adds(x,y,f);adds(y,x,0);
}
int dep[MAXN];
queue<int> Q;
bool bfs(int s,int t){
memset(dep,0,sizeof(dep));
Q.push(s);dep[s]=1;
while(!Q.empty()){
int top=Q.front();Q.pop();
for(int i=head[top];i;i=nex[i]){
int v=to[i];
if(dep[v]||fl[i]==0) continue;
dep[v]=dep[top]+1;
Q.push(v);
}
}
return dep[t];
}
int cur[MAXN];
int dfs(int x,int flow,int t){
if(x==t) return flow;
int tmp,used=0;
for(int &i=cur[x];i;i=nex[i]){
int v=to[i];
if(dep[v]!=dep[x]+1)continue;
tmp=dfs(v,min(flow-used,fl[i]),t);
used+=tmp;fl[i]-=tmp;fl[i^1]+=tmp;
if(used==flow) return flow;
}
if(!used) dep[x]=-1;
return used;
}
int dinic(int s,int t){
int ret=0;
while(bfs(s,t)){
memcpy(cur,head,sizeof(head));
ret+=dfs(s,INF,t);
}
return ret;
}
bool vis[MAXN*MAXN];
int main(){
freopen("phalanx.in","r",stdin);
freopen("phalanx.out","w",stdout);
n=rd();m=rd();
int S=n+n+1,T=n+n+2;
int x,y;
for(int i=1;i<=n;i++) add(S,i,1);
for(int i=1;i<=n;i++) add(i+n,T,1);
for(int i=1;i<=m;i++){
x=rd();y=rd();
add(x,y+n,1);
}
cout<<2*n*n-n*dinic(S,T)<<endl;
return 0;
}