题意:n只蚂蚁,n棵树,每只蚂蚁要连一棵树,连线(直线)不能相交,给出n只蚂蚁和n棵树的坐标,输出n只蚂蚁所配对的树的编号(1 <= n <= 100, -10000 <= 坐标x, y <= 10000)。

题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2044

——>>二分图最佳完美匹配第一题,挺简单,也挺容易写错。

很明显,蚂蚁为一个顶点集,树为一个顶点集,如果从蚂蚁向树匹配,那么最后输出前要先做一次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;
}

最新文章

  1. 2015.5.2-2015.5.8 Tip jQuery ,前端组件库,inline-block元素间距等
  2. css3之背景新属性
  3. 理解cookie的path和domain属性
  4. hdu Cup
  5. kaili 2.0 虚拟机修改ip
  6. SVN Server配置详解 及备份
  7. TWaver初学实战——如何在EasyUI中插入TWaver
  8. jquery 自定义tab
  9. JUnit4中的测试套件
  10. Sql Server专题一:索引(中)
  11. python运维开发(六)----模块续
  12. 读书笔记:《重来REWORK》
  13. UWP 分享用那个图标
  14. [转]CSS clear both清除浮动
  15. Docker(一)Linux开启你的Docker之旅
  16. java算法----排序----(7)堆排序
  17. form表单 获取与赋值
  18. centos7 部署 nginx+tomcat+MariaDB 环境并安装安全狗,使用natapp隧道
  19. [原创]Python/Django使用富文本编辑器XHeditor上传本地图片
  20. STM32F4XX devices vector table for EWARM toolchain.

热门文章

  1. 利用httpclient和多线程刷訪问量代码
  2. aop编程 环绕round
  3. 说说关于php内置函数curl_init()
  4. RVCT的Linux环境变量配置 ARM&#174; RVDS™ 4.1(b713)
  5. 手游接入Facebook的那些坑
  6. cloudflare的新waf,用Lua实现的
  7. WCF技术剖析之十五:数据契约代理(DataContractSurrogate)在序列化中的作用
  8. Delphi中运行时改变panel的位置及大小(通过wm_SysCommand来实现)
  9. WPF/Silverlight深度解决方案:(一)解锁被Storyboard束缚的关联属性
  10. Git 在小团队中的管理流程(转)