【BZOJ】【2661】【Beijing WC2012】连连看

时间:2022-05-14 15:13:27

网络流/费用流/二分图最大权匹配


  拆点费用流求最大权匹配……为什么我拿zyf和Hzwer的代码也交不过去……WA了那么多次……so sad

  求路过的神牛指导啊>_<万分感谢

 //BZOJ 2661
#include<cmath>
#include<vector>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define rep(i,n) for(int i=0;i<n;++i)
#define F(i,j,n) for(int i=j;i<=n;++i)
#define D(i,j,n) for(int i=j;i>=n;--i)
#define pb push_back
using namespace std;
inline int getint(){
int v=,sign=; char ch=getchar();
while(ch<''||ch>''){ if (ch=='-') sign=-; ch=getchar();}
while(ch>=''&&ch<=''){ v=v*+ch-''; ch=getchar();}
return v*sign;
}
const int N=,M=,INF=~0u>>;
typedef long long LL;
/******************tamplate*********************/
int n,m,a,b,ans,flow;
inline int gcd(int a,int b){return b ? gcd(b,a%b) : a;}
bool judge(int x,int y){
int q=x*x-y*y,s=sqrt(q);
if (s*s==q && gcd(y,s)==) return ;
return ;
}
struct edge{int from,to,v,c;};
struct Net{
edge E[M];
int head[N],next[M],cnt;
void ins(int x,int y,int z,int c){
E[++cnt]=(edge){x,y,z,c};
next[cnt]=head[x]; head[x]=cnt;
}
void add(int x,int y,int z,int c){
ins(x,y,z,c); ins(y,x,,-c);
}
int from[N],Q[M],d[N],S,T;
bool inq[N];
bool spfa(){
int l=,r=-;
F(i,,T) d[i]=INF;
d[S]=; Q[++r]=S; inq[S]=;
while(l<=r){
int x=Q[l++];
inq[x]=;
for(int i=head[x];i;i=next[i])
if(E[i].v> && d[x]+E[i].c<d[E[i].to]){
d[E[i].to]=d[x]+E[i].c;
from[E[i].to]=i;
if (!inq[E[i].to]){
Q[++r]=E[i].to;
inq[E[i].to]=;
}
}
}
return d[T]!=INF;
}
void mcf(){
int x=INF,y,z;
for(int i=from[T];i;i=from[E[i].from]){
// if (E[i].from==S) y=E[i].to;
// if (E[i].to==T) z=E[i].from-b;
x=min(x,E[i].v);
}
for(int i=from[T];i;i=from[E[i].from]){
E[i].v-=x;
E[i^].v+=x;
}
flow+=x;
ans+=x*d[T];
}
void init(){
scanf("%d%d",&a,&b);
cnt=; S=; T=;
F(i,a,b){
add(S,i,,);
add(i+b,T,,);
F(j,a,i-)
if(judge(i,j)) add(i,j+b,,-i-j);
}
while(spfa()) mcf();
printf("%d %d",flow,-ans);
}
}G1; int main(){
#ifndef ONLINE_JUDGE
freopen("2661.in","r",stdin);
freopen("2661.out","w",stdout);
#endif
G1.init();
return ;
}