CodeForces 289B Polo the Penguin and Matrix (贪心)
2016-07-26 10:50
501 查看
题意:给一个n*m的矩阵,给一个d值,你的目标是将矩阵里的每个数字变换成相等的数,你可以进行的操作是将每个数+d或者-d,如果不能实现这个目的,就输出-1,如果可以,输出操作次数
我的思路是将矩阵存到数组里,判断每个数与前一个数的差值是否为d的倍数来确定是否可以实现目标,如果可以,将数组排序取中位数,将每个数变成中位数,最后输出变换次数即可
代码如下
我的思路是将矩阵存到数组里,判断每个数与前一个数的差值是否为d的倍数来确定是否可以实现目标,如果可以,将数组排序取中位数,将每个数变成中位数,最后输出变换次数即可
代码如下
#include<cstdio> #include<algorithm> using namespace std; int a[10000+5]; int main() { int n,m,d; scanf("%d%d%d",&n,&m,&d); for(int i=1;i<=n*m;i++) scanf("%d",&a[i]); sort(a+1,a+1+n*m); for(int i=2;i<=n*m;i++) { int x=a[i]-a[i-1]; if(x%d!=0) {printf("-1\n");return 0;} } int mid=a[(n*m+1)/2]; int ans=0; for(int i=1;i<=n*m;i++) { int x=a[i]-mid; if(x<0) x=-x; ans+=(x/d); } printf("%d\n",ans); }
相关文章推荐
- Codeforces Round #197 (Div. 2)
- Codeforces Round #198 (Div. 1)
- Codeforces 405E Codeforces Round #238 (Div. 2)E
- Codeforces 407C Codeforces Round #239 (Div. 1)C
- 【WHUST 2016 Individual Contest #1】解题报告
- 【WHUST 2016 Individual Contest #2】解题报告
- 【WHUST 2016 Individual Contest #3 】解题报告
- CodeForces 449A - Jzzhu and Chocolate
- CodeForces 449 B. Jzzhu and Cities
- codeforces 618C. Constellation
- Codeforces Round #349 (Div. 2) - C
- Codeforces Round #361 (Div. 2)
- 7.13Codeforces Round #360 (Div. 2)
- Codeforces Round #363 (Div. 2)
- Codeforces Round #265 (Div. 2)
- Codeforces #310 div2 C. Case of Matryoshkas
- 状态压缩DP codeforces 244 Problem C. The Brand New Function 和 codeforces 165 E. Compatible Numbers
- codeforces 16 Problem E fish
- Codeforces Round332 部分题解
- CodeForces 603A_Alternative Thinking (DP)