A - Chess Placing

A. Chess Placing
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: “BWBW…BW”.

Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to .

In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.

Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).

Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.

The second line of the input contains integer numbers (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.

Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.

Examples
inputCopy
6
1 2 6
outputCopy
2
inputCopy
10
1 2 3 4 5
outputCopy
10

题解:

枚举一遍全挪到黑色再枚举一遍全挪到白色取最小值即可。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <ctime>

using namespace std;

const int maxn = 100+10;

int n,p[1007],sum[2]={0},cur[2]={1,2};

int main()
{
    cin>>n;
    for(int i=1;i<=n/2;i++) cin>>p[i];
    sort(p+1,p+1+n/2);
    for(int i=1;i<=n/2;i++,cur[0]+=2,cur[1]+=2)
    {
        sum[0] += abs(cur[0]-p[i]);
        sum[1] += abs(cur[1]-p[i]);
    }
    cout<<min(sum[0],sum[1])<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/q451792269/article/details/80703033