您的位置:首页 > 运维架构

poj 2536 Gopher II 二分匹配应用 匈牙利算法

2017-04-24 10:50 381 查看
题意:有某种动物n个,以及m个洞穴。给定n个动物坐标,以及m个洞穴坐标。每个动物有相同的运动速度v,单位是m/s。在老鹰来时,如果不能在s秒内(含s秒)躲进洞里,将会被吃,求怎么分配动物及洞穴,使得尽量少的动物被抓。

思路:建立结点,左边为动物,右边为洞穴,对于左边任意一个动物,若能够在s秒内躲进右边任意一个洞穴,则之间连一条边。接下来就是求最大匹配,用总数减去最大匹配数,就是最少被抓数量。

#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<cmath>
#include<iostream>
using namespace std;
const int maxn = 400;
struct edge
{
int from,to;
};
struct Pt
{
double x,y;
}pt[maxn];
vector<edge> edges;
vector<int> g[maxn];
int match[maxn],check[maxn];
int n,m,s,v;
bool dfs(int u)
{
for(int i=0;i<g[u].size();i++)
{
int v=edges[g[u][i]].to;
if(!check[v])
{
check[v]=1;
if(match[v]==-1||dfs(match[v]))
{
match[u]=v;
match[v]=u;
return true;
}
}

}
return false;
}
int Hungarian()
{
int ans=0;
memset(match,-1,sizeof(match));
for(int i=1;i<=n;i++)
{
if(match[i]==-1)
{
memset(check,0,sizeof(check));
if(dfs(i))ans++;
}

}
return ans;
}
double dist(int i,int j)
{
return sqrt((pt[i].x-pt[j].x)*(pt[i].x-pt[j].x)+
(pt[i].y-pt[j].y)*(pt[i].y-pt[j].y));
}
void addedge(int from,int to)
{
edges.push_back(edge{from,to});
edges.push_back(edge{to,from});
int m=edges.size();
g[from].push_back(m-2);
g[to].push_back(m-1);
}
int main()
{
//freopen("in.txt","r",stdin);
while(
4000
scanf("%d%d%d%d",&n,&m,&s,&v)!=EOF)
{
double x,y;
edges.clear();
for(int i=1;i<=n+m;i++)g[i].clear();
int i=1;
for(;i<=n;i++)
{
cin>>x>>y;
pt[i].x=x;
pt[i].y=y;
}
m=n+m;
for(i=n+1;i<=m;i++)
{
cin>>x>>y;
pt[i].x=x;
pt[i].y=y;
}
for(int i=1;i<=n;i++)
{
for(int j=n+1;j<=m;j++)
{
double dt=dist(i,j)/(v*1.0);
if(dt<=s)
{
addedge(i,j);
}
}
}
int ans=Hungarian();
printf("%d\n",n-ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: