• 【BZOJ3170】[Tjoi 2013]松鼠聚会 旋转坐标系


    【BZOJ3170】[Tjoi 2013]松鼠聚会

    有N个小松鼠,它们的家用一个点x,y表示,两个点的距离定义为:点(x,y)和它周围的8个点即上下左右四个点和对角的四个点,距离为1。现在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

    20

    题解:先旋转坐标系,然后切比雪夫距离就变成了曼哈顿距离。如何求曼哈顿距离中到所有点距离和最小的点呢?维护两个前缀和扫两遍即可。

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    typedef long long ll;
    const int maxn=100010;
    int n;
    ll sum,ans;
    struct node
    {
    	ll x,y,s;
    }p[maxn];
    inline int rd()
    {
    	int ret=0,f=1;	char gc=getchar();
    	while(gc<'0'||gc>'9')	{if(gc=='-')f=-f;	gc=getchar();}
    	while(gc>='0'&&gc<='9')	ret=ret*10+gc-'0',gc=getchar();
    	return ret*f;
    }
    bool cmpx(node a,node b)
    {
    	return (a.x==b.x)?(a.y<b.y):(a.x<b.x);
    }
    bool cmpy(node a,node b)
    {
    	return (a.y==b.y)?(a.x<b.x):(a.y<b.y);
    }
    int main()
    {
    	n=rd();
    	int i,a,b;
    	for(i=1;i<=n;i++)	a=rd(),b=rd(),p[i].x=a+b,p[i].y=b-a;
    	sort(p+1,p+n+1,cmpx);
    	for(sum=0,i=1;i<=n;i++)	p[i].s+=(i-1)*p[i].x-sum,sum+=p[i].x;
    	for(sum=0,i=n;i>=1;i--)	p[i].s+=sum-(n-i)*p[i].x,sum+=p[i].x;
    	sort(p+1,p+n+1,cmpy);
    	for(sum=0,i=1;i<=n;i++)	p[i].s+=(i-1)*p[i].y-sum,sum+=p[i].y;
    	for(sum=0,i=n;i>=1;i--)	p[i].s+=sum-(n-i)*p[i].y,sum+=p[i].y;
    	ans=1ll<<60;
    	for(i=1;i<=n;i++)
    		ans=min(ans,p[i].s);
    	printf("%lld",ans>>1);
    	return 0;
    }
  • 相关阅读:
    空格转换
    vuex学习
    css移动端适配方法
    数组以及数组常用方法
    21-canvas事件监听
    20-canvas之形变
    [转]session 跨域共享方案
    [转载] 从mysql,代码,服务器三个方面看mysql性能优化
    [计算机]Alan Perlis人物简介
    Python环境搭建及pip的使用
  • 原文地址:https://www.cnblogs.com/CQzhangyu/p/7391187.html
Copyright © 2020-2023  润新知