LA - 4043 - Ants
2024-10-11 16:15:33
题意:n只蚂蚁,n棵树,每只蚂蚁要连一棵树,连线(直线)不能相交,给出n只蚂蚁和n棵树的坐标,输出n只蚂蚁所配对的树的编号(1 <= n <= 100, -10000 <= 坐标x, y <= 10000)。
——>>二分图最佳完美匹配第一题,挺简单,也挺容易写错。
很明显,蚂蚁为一个顶点集,树为一个顶点集,如果从蚂蚁向树匹配,那么最后输出前要先做一次o(n)的映射,如果从树向蚂蚁匹配,则最后可直接输出。
建图:以n棵树为X点,以n只蚂蚁为Y点,权值w[i][j]为树i到蚂蚁j的距离的相反数(二分图最佳完美匹配求的是权和最大,而我们要的是权和最小(这样就不会有线段相交),所以权值取了相反数后变成了求二分图的最大完美匹配),跑一次KM就好。
#include <cstdio>
#include <cmath>
#include <algorithm> using namespace std; const int maxn = 100 + 10;
const double eps = 1e-10; int n, fa[maxn];
double w[maxn][maxn], Lx[maxn], Ly[maxn];
bool S[maxn], T[maxn]; struct Point{
double x, y;
Point(double x = 0, double y = 0):x(x), y(y){}
}; Point ant[maxn], tree[maxn]; double Dis(Point A, Point B){
return sqrt((A.x-B.x)*(A.x-B.x) + (A.y-B.y)*(A.y-B.y));
} bool match(int i){
S[i] = 1;
for(int j = 1; j <= n; j++) if(fabs(Lx[i]+Ly[j]-w[i][j]) < eps && !T[j]){
T[j] = 1;
if(!fa[j] || match(fa[j])){
fa[j] = i;
return 1;
}
}
return 0;
} void update(){
double a = 1 << 30;
for(int i = 1; i <= n; i++) if(S[i])
for(int j = 1; j <= n; j++) if(!T[j])
a = min(a, Lx[i]+Ly[j]-w[i][j]);
for(int i = 1; i <= n; i++){
if(S[i]) Lx[i] -= a;
if(T[i]) Ly[i] += a;
}
} void KM(){
for(int i = 1; i <= n; i++) fa[i] = Lx[i] = Ly[i] = 0;
for(int i = 1; i <= n; i++){
while(1){
for(int j = 1; j <= n; j++) S[j] = T[j] = 0;
if(match(i)) break;
else update();
}
}
} int main()
{
int first = 1;
while(scanf("%d", &n) == 1){
for(int i = 1; i <= n; i++) scanf("%lf%lf", &ant[i].x, &ant[i].y);
for(int i = 1; i <= n; i++) scanf("%lf%lf", &tree[i].x, &tree[i].y);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
w[i][j] = -Dis(tree[i], ant[j]); //计算树i与蚂蚁j的距离,并用其相反数作权值
KM();
if(first) first = 0;
else puts("");
for(int i = 1; i <= n; i++) printf("%d\n", fa[i]);
}
return 0;
}
最新文章
- 2015.5.2-2015.5.8 Tip jQuery ,前端组件库,inline-block元素间距等
- css3之背景新属性
- 理解cookie的path和domain属性
- hdu Cup
- kaili 2.0 虚拟机修改ip
- SVN Server配置详解 及备份
- TWaver初学实战——如何在EasyUI中插入TWaver
- jquery 自定义tab
- JUnit4中的测试套件
- Sql Server专题一:索引(中)
- python运维开发(六)----模块续
- 读书笔记:《重来REWORK》
- UWP 分享用那个图标
- [转]CSS clear both清除浮动
- Docker(一)Linux开启你的Docker之旅
- java算法----排序----(7)堆排序
- form表单 获取与赋值
- centos7 部署 nginx+tomcat+MariaDB 环境并安装安全狗,使用natapp隧道
- [原创]Python/Django使用富文本编辑器XHeditor上传本地图片
- STM32F4XX devices vector table for EWARM toolchain.
热门文章
- 利用httpclient和多线程刷訪问量代码
- aop编程 环绕round
- 说说关于php内置函数curl_init()
- RVCT的Linux环境变量配置 ARM&#174; RVDS™ 4.1(b713)
- 手游接入Facebook的那些坑
- cloudflare的新waf,用Lua实现的
- WCF技术剖析之十五:数据契约代理(DataContractSurrogate)在序列化中的作用
- Delphi中运行时改变panel的位置及大小(通过wm_SysCommand来实现)
- WPF/Silverlight深度解决方案:(一)解锁被Storyboard束缚的关联属性
- Git 在小团队中的管理流程(转)