codeforces B. Polo the Penguin and Matrix 解题报告

题目链接:http://codeforces.com/problemset/problem/289/B

题目意思:给出一个 n 行 m 列的矩阵和数值 d 。通过对矩阵里面的数进行 + d 或者 - d 的操作,是否可以使矩阵上的所有数相等。可以的话输出最少的操作步数,否则输出 -1。

      由于矩阵的排列对处理没什么影响,因此不需要用到二维数组存储。接着把矩阵中所有的数从小到大进行排序,要想算出最少的步数,很容易想到应该最中间的数(中位数)靠拢。最关键的是如何判断不能通过对矩阵中的数进行处理使得所有数相等。我的做法是,在将每个数向这个中位数靠拢的过程中,它们的差(绝对值)应该能被 d 除尽,一旦有一个不满足,就不可能通过调整使得所有数相等。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cmath>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 const int maxn = 10000 + 5;
 9 int a[maxn];
10 
11 int main()
12 {
13     int n, m, i, d;
14     while (scanf("%d%d%d", &n, &m, &d) != EOF)
15     {
16         for (i = 0; i < n*m; i++)
17             scanf("%d", &a[i]);
18         sort(a, a+n*m);
19         if (a[0] == a[n*m-1])  // 常数列,不需要调整为0
20             printf("0\n");
21         else
22         {
23             int mid = a[n*m/2];
24             int flag, ans;
25             flag = ans = 0;
26             for (i = 0; i < n*m; i++)
27             {
28                 if (abs(a[i]-mid) % d)
29                 {
30                     flag = 1;
31                     break;
32                 }
33                 else
34                     ans += abs(a[i]-mid) / d;
35             }
36             if (flag)
37                 printf("-1\n");
38             else
39                 printf("%d\n", ans);
40         }
41     }
42     return 0;
43 }  

 

     

posted @ 2014-02-07 21:15  windysai  阅读(352)  评论(0编辑  收藏  举报