您的位置:首页 > 其它

[NOIP模拟] 匹配

2017-10-16 21:17 387 查看

题目大意 :

    给出一些白点和黑点,现要求白点在黑点的右下方,最终匹配黑白点之间的曼哈顿距离的最小值, 保证有解。

输入简述 :

    给出整数 n, 和 n 个黑点坐标和白点坐标。

输出简述 :

    输出一个整数最小距离。

题解 :

    讲真做到这道题的时候还没有反应过来,你仔细分析一下这个曼哈顿的距离,因为题目保证有解,所以我们可以将距离这么写: dismin=∑i=1n|xblank−i−xwhite−i|+|yblank−i−ywhite−i|

然后题目说了保证有解, 那么一个黑点的右下方一定会找到一个白点, 那么我们的公式就可以展开 :

dismin=∑i=1nxwhite−i−xblank−i+yblank−i−ywhite−i

于是得证我们只需在坐标上加加减减就可以了。当然我考试的时候傻逼了。

代码 :

这里我就手打一下,没有编译过。

#include <bits/stdc++.h>
#define LL long long
using namespace std;

inline int read() {
int i = 0, f = 1;
char ch = getchar();
while(!isdigit(ch)) {
if(ch == '-') f = -1; ch = getchar();
}
while(isdigit(ch)) {
i = (i << 3) + (i << 1) + ch - '0'; ch = getchar();
}
return i * f;
}

int main() {
int n = read();
LL ans = 0;
for(int i = 1; i <= n; ++i) ans -= read(), ans += read();
for(int i = 1; i <= n; ++i) ans += read(), ans -= read();
cout<<ans<<'\n';
}


下面是我的考试代码 :

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <ctime>
#include <map>
#include <vector>
#define LL long long
using namespace std;

inline int read() {
int i = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9') {
if(ch == '-') f = -1; ch = getchar();
}
while(ch >= '0' && ch <= '9') {
i = (i << 3) + (i << 1) + ch - '0'; ch = getchar();
}
return i * f;
}

const int MAXN = 5e4 + 5;
struct point {
int x, y;
};
point w[MAXN], b[MAXN];
int vis[MAXN], head;

inline bool comp(const point & a, const point & b) {
if(a.x == b.x) return a.y < b.y;
return a.x < b.x;
}

int main() {
int n = read();
for(int i = 1; i <= n; ++i) b[i].x = read(), b[i].y = read();
for(int i = 1; i <= n; ++i) w[i].x = read(), w[i].y = read();
sort(w + 1, w + n + 1, comp); sort(b + 1, b + n + 1, comp);
head = 1; LL ans = 0;
for(int i = 1; i <= n; ++i) {
if(b[i].y < w[i].y) ans = ans - (LL)(w[i].y - b[i].y) * 2;
ans += (LL)abs(w[i].y - b[i].y) + (LL)abs(b[i].x - w[i].x);
}
cout<<ans<<'\n';
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  NOIP模拟 简单题