985A Chess Placing

A. Chess Placing
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard 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 ≤ 100n 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
input
Copy
6
1 2 6
output
Copy
2
input
Copy
10
1 2 3 4 5
output
Copy
10
Note

In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.

In the second example the possible strategy is to move  in 4 moves, then  in 3 moves,  in 2 moves and  in 1 move.


题意:给你只有一行的棋盘,有n列,一定是偶数。奇数的位置为黑色,偶数是白色的。

然后放入n/2个棋子,让你让放的棋子全部是都在黑色(奇数)的或者白色(偶数)上面。输出最小的移动步数。

题解:暴力  对输入的n/2个棋子先排序,x记录所有棋子移动到奇数的步数,y记录移动到偶数的步数。两个里面取最小的。


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,a[110],x=0,y=0;
    cin>>n;
    for(int i=1; i<=n/2; i++)
        cin>>a[i];
    sort(a+1,a+n/2+1);
    for(int i=1; i<=n/2; i++)
    {
        x+=abs(a[i]-(i*2-1));///排序后把每个没在奇数位置距离和加起来(移动到奇数的步数)
        y+=abs(a[i]-i*2);///记录移动到偶数的步数
    }
    cout<<min(x,y);
    return 0;
}
n=int(input())
a=list(map(int,input().split(' ')))
a=sorted(a)
x=0
y=0
for i in range(n//2):
	x+=abs(a[i]-i*2-1)
	y+=abs(a[i]-i*2-2)
print(min(x,y))


猜你喜欢

转载自blog.csdn.net/memory_qianxiao/article/details/80498887