Codeforces 985A 题解

题意

有一个长度为\(n\)(\(n\)为偶数)的棋盘,黑白相间,类似于BWBW...BW.现有\(n/2\)个位置有棋子,每次只能向左或向右移动一个棋子一步,棋子不能重叠或移出棋盘.求最少要用多少次才能使所有棋子所在的格子颜色相同.

题解

显然只有两种方案:\(1,3,5,\cdots,n-1\)\(2,4,6,\cdots,n\).因为不能越过其他棋子,所以移动步数确定.那么直接讨论两种情况即可.

代码

#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <algorithm>
using namespace std;
#define gc getchar
inline void read(int &x){ // 读入优化
    register bool f;
    register char ch;
    for (f = false, ch = gc(); !isdigit(ch); ch = gc()) if (ch == '-') f = true;
    for (x = 0; isdigit(ch); ch = gc()) x = ((x + (x << 2)) << 1) + (ch ^ '0');
    if (f) x = -x;
}
const int N = 105;
int n, a[N], s1, s2;
inline int abs(int x){ // 求x的绝对值
    return x > 0 ? x : -x;
}
int main(){
    read(n), n >>= 1;
    for (register int i = 1; i <= n; ++i) read(a[i]);
    sort(a + 1, a + 1 + n); // 排序,最左边的棋子一定是移动到最左边的黑/白格子的.
    for (register int i = 1; i <= n; ++i)
        s1 += abs(a[i] - ((i << 1) - 1)), s2 += abs(a[i] - (i << 1));
    // s1表示第一种情况,s2表示第二种情况
    return printf("%d", s1 < s2 ? s1 : s2), 0;
}

转载于:https://www.cnblogs.com/rill7747/p/9094104.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值