codeforces 985A Chess Placing

题意:

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

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

思路:

其实不用管移动棋子的限制。

枚举全是黑色和全是白色两种情况。

每次枚举,找离当前格子最近的没有被占用的格子,然后标记并且取消当前格子的标记。

代码:

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

猜你喜欢

转载自www.cnblogs.com/kickit/p/9070385.html