HDU4311 Meeting point-1(曼哈頓距離),hdu4311point-1

來源:互聯網
上載者:User

HDU4311 Meeting point-1(曼哈頓距離),hdu4311point-1

題目連結:

http://acm.hdu.edu.cn/showproblem.php?pid=4311

題意:

給定n個點,選其中的一個點作為起點,然後使其他點到這個點的曼哈頓距離最小,求這個最小的距離


分析:

我們設P作為這個點作為起點

然後 ans = sum(abs|pi.x-p.x|+|pi.y-p.y| )(1<=i<=n)

我們可以對其分別按x,y進行排序,就可以去掉絕對值符號

然後化簡後的公式就可以變成

設這個點在按x排完序後的位置為i;

設tot[i],表示到序號i為止的點的橫座標的和。

ansx = (i-1)*p.x+(tot[n]-tot[i])-(n-i)*p.x

同理可以求出

設這個點在按t排完序後的位置為i;

ansy= (i-1)*p.y+(tot[n]-tot[i])-(n-i)*p.y

ans = ansx + ansy

然後取最小的ans 即可

時間複雜度為O(nlog(n));


代碼如下:

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;typedef long long LL;const int maxn = 1e5+10;struct point{    int x,y;    LL sum;}p[maxn];bool cmp1(point A,point B){    if(A.x<B.x) return true;    if(A.x==B.x&&A.y<B.y) return true;    return false;}bool cmp2(point A,point B){    if(A.y<B.y) return true;    if(A.y==B.y&&A.y<B.y) return true;    return false;}int main(){    int t,n;    scanf("%d",&t);    while(t--){        scanf("%d",&n);        LL sum=0;        for(int i=1;i<=n;i++){            scanf("%d%d",&p[i].x,&p[i].y);            p[i].sum=0;        }        sort(p+1, p+1+n, cmp1);        for (LL i = 1; i <= n; ++i) {            p[i].sum += (i-1) * p[i].x - sum;            sum += p[i].x;        }        sum = 0;        for (LL i = n; i >= 1; --i) {            p[i].sum += sum - (n-i) * p[i].x;            sum += p[i].x;        }        sum = 0;        sort(p+1, p+1+n, cmp2);        for (LL i = 1; i <= n; ++i) {            p[i].sum += (i-1) * p[i].y -sum;            sum += p[i].y;        }        sum = 0;        LL ans = 1LL<<62;        for (LL i = n; i >= 1; --i) {            p[i].sum += sum - (n-i) * p[i].y;            ans = min(ans, p[i].sum);            sum += p[i].y;        }        printf("%I64d\n",ans);    }    return 0;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.