1490. Soldiers

Title Description

In Gridland countries, there are N soldiers in different locations. Place on all of the country with two coordinates (X, Y) to represent. Soldiers can move once, each soldier can be up, down, left, or right to a unit length, so that he will be able to alter their X or Y 1 or -1.
The soldiers want to get into a horizontal line, close to each other, so that their final position (X, Y), (X + 1, Y), ..., (X + N, Y)). Finally, the order of soldiers horizontal line and the integer X and Y, are arbitrary.

Now the goal is to find the minimum number of moving such a configuration soldiers.

Two or more soldiers are not in the same place at the same time.

Entry

The first line of the input file soldiers.in contains an integer N, 1 <= N <= 10000, N is the number of soldiers. After the input file should contain N lines soldiers initial position, for each i, 1 <= i <= N, the first row I + 1 input file contains two space-separated integers x [i], y [i ], they represent the coordinates of the soldiers I, -10000 <= x [i], y [i] <= 10000.

Export

Soldiers.out only one row of the output file, so that it is moved to the minimum number of soldiers moving horizontal lines adjacent to each other.

Code

# include<cstdio>
# include<cmath>
# include<algorithm>
# include<cctype>
using namespace std;
const int maxn = 1e4;
int x[maxn + 10],y[maxn + 10];
inline int read()
{
    int ret = 0,w = 0; 
    char ch = 0;
    while(!isdigit(ch)) 
    {
        w |= ch == '-';
        ch = getchar();
    }
    while(isdigit(ch)) 
    {
        ret = (ret << 3) + (ret << 1) + (ch ^ 48);
        ch = getchar();
    }
    return w ? -ret : ret;
}
inline void write(int x)
{
     if(x < 0) 
        putchar('-'),x = -x;
     if(x > 9) 
        write(x / 10);
     putchar(x % 10 + '0');
}
int main()
{
    freopen("soldiers.in","r",stdin);
    freopen("soldiers.out","w",stdout);
    int n,i,k,ans;
    n = read();
    for(i = 1;i <= n;i++)
    {
        x[i] = read();
        y[i] = read();
    }
    sort(x + 1,x + n + 1);
    sort(y + 1,y + n + 1);
    for(i = 1;i <= n;i++)
        x[i] -= i;
    sort(x + 1,x + n + 1);
    ans = 0,k = (n + 1) / 2;
    for(i = 1;i <= n;i++)
        ans += abs(x[i] - x[k]) + abs(y[i] - y[k]);
    write(ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_40155097/article/details/95304339
Recommended