BZOJ3170: [Tjoi2013]松鼠聚会(切比雪夫距离转曼哈顿距离)
生活随笔
收集整理的這篇文章主要介紹了
BZOJ3170: [Tjoi2013]松鼠聚会(切比雪夫距离转曼哈顿距离)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Time Limit:?10 Sec??Memory Limit:?128 MB
Submit:?1524??Solved:?803
[Submit][Status][Discuss]
-4 -1
-1 -2
2 -4
0 2
0 3
5 -2
Submit:?1524??Solved:?803
[Submit][Status][Discuss]
Description
有N個小松鼠,它們的家用一個點x,y表示,兩個點的距離定義為:點(x,y)和它周圍的8個點即上下左右四個點和對角的四個點,距離為1?,F在N個松鼠要走到一個松鼠家去,求走過的最短距離。
Input
第一行給出數字N,表示有多少只小松鼠。0<=N<=10^5
下面N行,每行給出x,y表示其家的坐標。
-10^9<=x,y<=10^9
Output
表示為了聚會走的路程和最小為多少。
Sample Input
6-4 -1
-1 -2
2 -4
0 2
0 3
5 -2
Sample Output
20HINT
Source
emmm,題目給出的是切比雪夫距離,我們需要轉化成曼哈頓距離
對于坐標中的每個點$(x, y)$,轉化為曼哈頓距離之后是$(\frac{x + y}{2}, \frac{x - y}{2})$
然后枚舉一個點$k$,我們需要算的是$\sum_{i = 1}^N |x_k - x_i| + |y_k - y_i|$
暴力拆開之后發現可以用前綴和優化
代碼寫出來很漂亮qwq。
#include<cstdio> #include<algorithm> #define LL long long using namespace std; const int MAXN = 1e5 + 10; const LL INF = 1e18 + 10; inline int read() {char c = getchar();int x = 0,f = 1;while(c < '0' || c > '9'){if(c == '-')f = -1;c = getchar();}while(c >= '0' && c <= '9'){x = x * 10 + c - '0',c = getchar();}return x * f; } LL N, x[MAXN], y[MAXN], sortx[MAXN], sorty[MAXN], sumx[MAXN], sumy[MAXN]; LL QueryX(int l, int r) {return sumx[r] - sumx[l - 1]; } LL QueryY(int l, int r) {return sumy[r] - sumy[l - 1]; } LL calc(LL k) {LL posx = lower_bound(sortx + 1, sortx + N + 1, x[k]) - sortx,posy = lower_bound(sorty + 1, sorty + N + 1, y[k]) - sorty;return posx * sortx[posx] - QueryX(1, posx) - (N - posx) * sortx[posx] + QueryX(posx + 1, N) + posy * sorty[posy] - QueryY(1, posy) - (N - posy) * sorty[posy] + QueryY(posy + 1, N); } int main() { #ifdef WIN32freopen("a.in", "r", stdin); #endifN = read();for(int i = 1; i <= N; i++) {int a = read(), b = read();x[i] = sortx[i] = a + b,y[i] = sorty[i] = a - b; }sort(sortx + 1, sortx + N + 1);sort(sorty + 1, sorty + N + 1);for(int i = 1; i <= N; i++) sumx[i] = sumx[i - 1] + sortx[i],sumy[i] = sumy[i - 1] + sorty[i];LL ans = INF;for(int i = 1; i <= N; i++)ans = min(ans, calc(i));printf("%lld", ans >> 1);return 0; }?
總結
以上是生活随笔為你收集整理的BZOJ3170: [Tjoi2013]松鼠聚会(切比雪夫距离转曼哈顿距离)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小目标三、存储数据的表结构
- 下一篇: 20180927-1