Poj 1723 SOLDIERS

来源:互联网 发布:提升美工欣赏 编辑:程序博客网 时间:2024/06/07 10:11

题目连接:http://poj.org/problem?id=1723

本题是排序题。

求士兵从自己的位置走到紧挨着的同一行的最小步数。

可以证明,中位数是最小的。可以从y方向和x方项分别讨论,相互不影响。对于x方向有些绕弯,我们需要保持他们的相对顺序不变化,选择排好序的序列作为参照点,然后求中位数即可。

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>#include <algorithm>#include <stack>#include <queue>using namespace std;int x[10005];int y[10005];int a[100005];int main(){#ifndef ONLINE_JUDGE    freopen("in.txt","r",stdin);#endif    int n;    while(scanf(" %d",&n)!=EOF)    {        for(int i=0;i<n;i++)        {            scanf(" %d %d",&x[i],&y[i]);        }        sort(y,y+n);        int yt = y[n/2];        int sum = 0;        for(int i=0;i<n;i++)        {            sum += abs(y[i] - yt);        }        sort(x,x+n);        for(int i=0;i<n;i++)        {            a[i] = x[i] - i;        }        sort(a,a+n);        int at = a[n/2];        for(int i=0;i<n;i++)        {            sum += abs(a[i] - at);        }        printf("%d\n",sum);    }    return 0;}


原创粉丝点击