codeforces 289B - Polo the Penguin and Matrix 二分+dp
2014-07-30 07:59
453 查看
题意:给你一个序列,每一次可以对序列里面任意数+d 或者 -d 问你最少多少步能够使得数列里面所有的数相等
解题思路:从 1 - 10000 枚举这个数,二分找数列中小于等于它的最大的那个数,然后求前缀和以后刻意快速求出差值和的绝对值,差值和/d 就是我们所求数。
解题代码:
View Code
解题思路:从 1 - 10000 枚举这个数,二分找数列中小于等于它的最大的那个数,然后求前缀和以后刻意快速求出差值和的绝对值,差值和/d 就是我们所求数。
解题代码:
// File Name: 289b.cpp // Author: darkdream // Created Time: 2014年07月29日 星期二 22时33分11秒 #include<vector> #include<list> #include<map> #include<set> #include<deque> #include<stack> #include<bitset> #include<algorithm> #include<functional> #include<numeric> #include<utility> #include<sstream> #include<iostream> #include<iomanip> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<ctime> using namespace std; int a[10005]; int sum[10005]; int n , m ,d; int find(int x) { int l = 1, r = n; while(l <= r) { int m = (l+r)/2; if(a[m] > x) { r = m -1; }else { l = m + 1; } } return r; } int main(){ scanf("%d %d %d",&n,&m,&d); n = n * m ; sum[0] = 0 ; for(int i = 1;i <= n ;i ++) { scanf("%d",&a[i]); } sort(a+1,a+1+n); int M = 1e9 ; int ok = 1; sum[1] = a[1]; for(int i = 2;i <= n;i ++) { sum[i] = sum[i-1] + a[i]; if((a[i]-a[i-1])%d != 0 ) ok = 0; } if(ok) { ok = 0; for(int i = 1 ;i <= 10000;i ++) { int k = find(i); if(k == 0 ) continue; int ans = i*k - sum[k] +(sum -sum[k] -(n-k)*i); if( ans%d == 0 && ans/d <= M) { M = ans/d; // printf("%d %d %d %d\n",ans,i,k,M); ok = 1; } } } if(ok ==1 ) printf("%d\n",M); else printf("-1\n"); return 0; }
View Code
相关文章推荐
- codeforces 289 B. Polo the Penguin and Matrix
- Codeforces-289b J Polo the Penguin and Matrix
- codeforces 289 B. Polo the Penguin and Matrix
- codeforces#289_B Polo the Penguin and Matrix
- Codeforces-289a I Polo the Penguin and Segments
- CodeForces 288C Polo the Penguin and XOR operation
- Codeforces Polo the Penguin and Matrix
- codeforces#289_B Polo the Penguin and Matrix
- CodeForces 288C Polo the Penguin and XOR operation (位运算,异或)
- CodeForces 288C - Polo the Penguin and XOR operation(思维)
- codeforces 288A:Polo the Penguin and Strings
- B. Polo the Penguin and Matrix
- CodeForces 288C - Polo the Penguin and XOR operation
- CodeForces 289A Polo the Penguin and Segments
- Codeforces Round #177 (Div. 1) B - Polo the Penguin and Houses
- Codeforces 682C Alyona and the Tree(树形DP)
- CF_288B_PoloThePenguinAndHouses
- Codeforces Round #177 (Div. 1) C. Polo the Penguin and XOR operation(贪心)
- Codeforces 601C Kleofáš and the n-thlon(dp)
- A. Polo the Penguin and Strings