[bzoj3170][Tjoi2013]松鼠聚会【切比雪夫距离】

【题目链接】
  https://www.lydsy.com/JudgeOnline/problem.php?id=3170
【题解】
  首先将切比雪夫距离转换为曼哈顿距离。
  把每个点的坐标变为 (x+y2,xy2) ( x + y 2 , x − y 2 ) 后曼哈顿距离等于之前的切比雪夫距离。
  证明:
  设切比雪夫距离为 a a ,曼哈顿距离为 b b ,两个点的坐标为 (x1,y1),(x2,y2) ( x 1 , y 1 ) , ( x 2 , y 2 )
  那么有 a=max(x1x2,x2x1,y1y2,y2y1) a = m a x ( x 1 − x 2 , x 2 − x 1 , y 1 − y 2 , y 2 − y 1 )
  设 x3=x1+y12,x4=x2+y22,y3=x3y32,y4=x2y22 x 3 = x 1 + y 1 2 , x 4 = x 2 + y 2 2 , y 3 = x 3 − y 3 2 , y 4 = x 2 − y 2 2
  那么有
   b=max(x3x4+y3y4,x3x4+y4y3,x4x3+y3y4,x4x3+y4y3) b = m a x ( x 3 − x 4 + y 3 − y 4 , x 3 − x 4 + y 4 − y 3 , x 4 − x 3 + y 3 − y 4 , x 4 − x 3 + y 4 − y 3 )
  展开得 b=max(x1x2,x2x1,y1y2,y2y1) b = m a x ( x 1 − x 2 , x 2 − x 1 , y 1 − y 2 , y 2 − y 1 )
  所以 a=b a = b
  转换为曼哈顿距离之后,就可以横纵坐标分开算+扫描线了。
  时间复杂度 O(NlogN) O ( N l o g N )
【代码】

/* - - - - - - - - - - - - - - -
    User :      VanishD
    problem :   [bzoj3170]
    Points :    Chebyshev Distance
- - - - - - - - - - - - - - - */
# include 
# define    ll      long long
# define    N       100100
using namespace std;
const int inf = 0x3f3f3f3f, INF = 0x7fffffff;
const ll  infll = 0x3f3f3f3f3f3f3f3fll, INFll = 0x7fffffffffffffffll;
int read(){
    int tmp = 0, fh = 1; char ch = getchar();
    while (ch < '0' || ch > '9'){ if (ch == '-') fh = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9'){ tmp = tmp * 10 + ch - '0'; ch = getchar(); }
    return tmp * fh;
}
struct Node{
    ll x, y;
    int id;
}p[N];
ll ans[N];
int n;
bool cmpx(Node x, Node y){ return x.x < y.x; }
bool cmpy(Node x, Node y){ return x.y < y.y; }
int main(){
//  freopen(".in", "r", stdin);
//  freopen(".out", "w", stdout);
    n = read();
    for (int i = 1; i <= n; i++){
        ll x = read(), y = read();
        p[i].x = x + y, p[i].y = x - y;
        p[i].id = i;
    }
    sort(p + 1, p + n + 1, cmpx);
    ll dis0 = 0, dis1 = 0, cnt0 = n - 1, cnt1 = 0;
    for (int i = 2; i <= n; i++) dis0 += p[i].x - p[1].x;
    for (int i = 1; i <= n; i++){
        ans[p[i].id] = dis0 + dis1;
        if (i != n){
            dis0 = dis0 - 1ll * cnt0 * (p[i + 1].x - p[i].x);
            cnt0--; cnt1++;
            dis1 = dis1 + 1ll * cnt1 * (p[i + 1].x - p[i].x);
        }
    }
    sort(p + 1, p + n + 1, cmpy);
    dis0 = 0, dis1 = 0, cnt0 = n - 1, cnt1 = 0;
    for (int i = 2; i <= n; i++) dis0 += p[i].y - p[1].y;
    for (int i = 1; i <= n; i++){
        ans[p[i].id] += dis0 + dis1;
        if (i != n){
            dis0 = dis0 - 1ll * cnt0 * (p[i + 1].y - p[i].y);
            cnt0--; cnt1++;
            dis1 = dis1 + 1ll * cnt1 * (p[i + 1].y - p[i].y);
        }
    }
    ll final = INFll;
    for (int i = 1; i <= n; i++)
        final = min(final, ans[i] / 2);
    printf("%lld\n", final);
    return 0;
}

你可能感兴趣的:(【切比雪夫距离】)