蚂蚁:费用流做法
题目描述
平面上共有2*N个点,N个是白点,N个是黑点。
对于每个白点,找到一个黑点,把二者用线连起来,要求最后所有线段都不想交,求一种方案。
样例
in:
5
-42 58
44 86
7 28
99 34
-13 -59
-47 -44
86 74
68 -75
-68 60
99 -60
out:
4
2
3
5
1
算法1:KM
出门左转,这里就不说了。
算法2:费用流
建一个S,T
连S与集合A容量为1,边权为0的边,
连T与集合B容量为1,边权为0的边。
再跑一遍费用流就好了
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const double eps=1e-8;
const int maxn=205,maxm=1000005;
const double INF=0x3f3f3f3f;
struct EdgeNode {
int from,to,flow,next;
double cost;
} edge[maxm];
int head[maxn],cnt;
void add(int x,int y,int z,double c) {
edge[cnt].from=x;edge[cnt].to=y;edge[cnt].flow=z;edge[cnt].cost=c;edge[cnt].next=head[x];head[x]=cnt++;
edge[cnt].from=y;edge[cnt].to=x;edge[cnt].flow=0;edge[cnt].cost=-c;edge[cnt].next=head[y];head[y]=cnt++;
}
int dcmp(double x) {
if(fabs(x)<eps)return 0;
else return x<0?-1:1;
}
int S,T,n,m;
double d[maxn];
int in[maxn],pre[maxn];
queue<int>Q;
bool spfa(int S,int T) {
int u,v,f;
double c;
while(!Q.empty())Q.pop();
memset(in,0,sizeof(in));
for(int i=0; i<maxn; i++)d[i]=INF;
d[S]=0;
Q.push(S);
while(!Q.empty()) {
u=Q.front();
Q.pop();
in[u]=0;
for(int i=head[u]; i!=-1; i=edge[i].next) {
v=edge[i].to;
f=edge[i].flow;
c=edge[i].cost;
if(f&&dcmp(d[u]+c-d[v])<0) {
d[v]=d[u]+c;
pre[v]=i;
if(!in[v]) {
in[v]=1;
Q.push(v);
}
}
}
}
if(d[T]==INF)return false;
return true;
}
double MCMF(int S,int T,int need=0) {
int u;
int max_flow=0;
double min_cost=0;
while(spfa(S,T)) {
int flow=INF;
u=T;
while(u!=S) {
flow=min(flow,edge[pre[u]].flow);
u=edge[pre[u]].from;
}
u=T;
max_flow+=flow;
min_cost+=d[T]*flow;
while(u!=S) {
edge[pre[u]].flow-=flow;
edge[pre[u]^1].flow+=flow;
u=edge[pre[u]].from;
}
}
return min_cost;
}
struct p {
double x,y;
} a[105],b[105];
int chu[maxn];
double js(p a,p b) {
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
int main() {
int i,x,y,j;
while(~scanf("%d",&n)) {
cnt=0;
memset(head,-1,sizeof(head));
S=0,T=2*n+1;
for(i=1; i<=n; i++) scanf("%lf%lf",&a[i].x,&a[i].y);
for(i=1; i<=n; i++) scanf("%lf%lf",&b[i].x,&b[i].y);
for(i=1; i<=n; i++) add(S,i,1,0);
for(i=1; i<=n; i++) add(n+i,T,1,0);
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
add(i,n+j,1,js(a[i],b[j]));
MCMF(S,T);
for(i=0; i<cnt; i++) {
x=edge[i].from,y=edge[i].to;
if(x>0&&x<=n&&y>n&&y<=2*n)
if(edge[i].flow==0)chu[x]=y-n;
}
for(i=1; i<=n; i++) printf("%d\n",chu[i]);
}
return 0;
}