→题目链接←
二分图好像是比网络流好写...
然而我并不会
所以直接把网络流模板搞过来了
行连向列,流量为inf
然后所有的行和源点连,流量为1
所有的列和汇点连,流量为1
然后跑网络流/二分图就行
不管空间大小的代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<deque>
#include<vector>
#include<queue>
#include<cstring>
#define ll long long
#define inf 0x3f3f3f
using namespace std;
struct node{
int to,num;
}edge[440000];
int n,m;
int pn=1;
vector<int>v[110000];
int edgenum=0;
int d[110000];
void link(int x,int y,int z){
node t;
t.to=y;
t.num=z;
edge[edgenum]=t;
v[x].push_back(edgenum);
edgenum++;
t.to=x;
t.num=0;
edge[edgenum]=t;
v[y].push_back(edgenum);
edgenum++;
}
bool bfs(){
memset(d,-1,sizeof(d));
d[0]=1;
queue<int>q;
q.push(0);
while(!q.empty()){
int t=q.front();
q.pop();
if(t==pn)continue;
for(int i=0; i<v[t].size(); i++){
int x=v[t][i];
int to=edge[x].to;
int num=edge[x].num;
if(num==0 || d[to]!=-1)continue;
d[to]=d[t]+1;
q.push(to);
}
}
if(d[pn]!=-1)return true;
return false;
}
ll dfs(int x,int y){
if(x==pn || y==0)return y;
ll sum=0;
for(int i=0; i<v[x].size(); i++){
int j=v[x][i];
int to=edge[j].to;
int num=edge[j].num;
if(num){
if(d[to]!=d[x]+1)continue;
ll k=dfs(to,min(num,y));
if(k==0)continue;
y-=k;
sum+=k;
edge[j].num-=k;
edge[j^1].num+=k;
if(y==0)break;
}
}
if(sum==0)d[x]=-1;
return sum;
}
long long ans=0;
int main(){
scanf("%d%d",&n,&m);
for(int i=1; i<=m; i++){
int x,y;
scanf("%d%d",&x,&y);
link(x,y+n,inf);
}
for(int i=1; i<=n; i++){
link(0,i,1);
}
for(int i=n+1; i<=n*2; i++){
link(i,n*2+1,1);
}
pn+=n*2;
while(bfs())ans+=dfs(0,inf);
printf("%lld\n",ans);
return 0;
}