赞
踩
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).
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.
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
6 1 2 6
2
10 1 2 3 4 5
10
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))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。