codeforces 985A Chess Placing

题意:

移动最少的步数,使得所有的棋子在同一颜色的格子中。

每次一个棋子只能向左或者向右移动一步,不能移到有棋子的格子中。

思路:

枚举全黑和全白的情况。

对于每一个需要移动的棋子,它移动到的位置一定是从1开始第一个可以移动的位置,不交叉移动,保证了步数最小。

代码:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <algorithm>
 4 using namespace std;
 5 const int N = 105;
 6 int v[N],g[N];
 7 int mabs(int x)
 8 {
 9     return x >= 0 ? x : -x;
10 }
11 int main()
12 {
13     int n;
14     scanf("%d",&n);
15     for (int i = 0;i < n / 2;i++)
16     {
17         int x;
18         scanf("%d",&x);
19         v[x] = g[x] = 1;
20     }
21     int ans = 0;
22     for (int i = 1;i <= n;i++)
23     {
24         int ma = -1;
25         if (i % 2 && g[i])
26         {
27             for (int j = 1;j <= n;j++)
28             {
29                 if (j % 2 == 0 && !g[j])
30                 {
31                     ma = j;
32                     break;
33                 }
34             }
35             ans += mabs(ma - i);
36             g[ma] = 1;
37             g[i] = 0;
38         }
39     }
40     int cnt = 0;
41     for (int i = 1;i <= n;i++)
42     {
43         int ma = -1;
44         if (i % 2 == 0 && v[i])
45         {
46             for (int j = 1;j <= n;j++)
47             {
48                 if (j % 2 && !v[j])
49                 {
50                     ma = j;
51                     break;
52                 }
53             }
54             cnt += mabs(ma - i);
55             v[ma] = 1;
56             v[i] = 0;
57         }
58     }
59     printf("%d\n",min(ans,cnt));
60     return 0;
61 }

 

posted @ 2018-05-22 09:14  qrfkickit  阅读(256)  评论(0编辑  收藏  举报