Codeforces Round #653 (Div. 3) D. Zero Remainder Array

  • 題意
    給定一個長度爲n的數組nums
    初始化一個x = 0, 每次你可以有兩種操作:
    1)x ++
    2)nums 任意一個元素 + x。其中每個元素最多加一次x。
    最終目的是讓數組中每個元素都能被給定的一個k整除。
  • 思路 :
    對於一個數 tmp,我們考慮兩種情況:
    1) tmp < k
    若是tmp + x mod k = 0, 則可以得到 tmp = A*k - x.
    可知如果要得到結果,x from 1 to k 這樣的更新迭代期間,便可讓tmp得到最終結果。
    如果其中有兩個相同數值的tmp,則在 x from 1 to k 期間,使其中一個數字滿足條件,然後在 x from k to 2k期間,使得另外一個數得到滿足。
    可以發現需要的迭代次數res 與 相同數值tmp的個數 num之間的關係是res = num。而使得num個數都能滿足要求,x最終的值爲:
    x = (res-1)*k + (k - tmp)。因爲第一次x 更新到 k - tmp時,滿足一個tmp,然後再迭代 k個數,可以滿足另一個tmp。
    2)tmp > k
    當tmp > k時,其與k之間的距離便是 k - tmp%k。
    所以可以得到,x = (res-1) * k + (k - tmp%k).
    其中的res 是 tmp%k相同的數。
  • 代碼:
#include "bits/stdc++.h"
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define pb push_back
typedef long long ll;
const int maxn = 1e4 + 7;
const int INF =INT_MAX;
const double EPS = 10;
// #define _DEBUG

int main(){
#ifdef _DEBUG
    freopen("./Files/in.txt", "r", stdin);
    freopen("./Files/out.txt", "w", stdout);
#endif
    ios::sync_with_stdio(0);
    cin.tie(0);

    int T;
	cin >> T;
    map<int, int> cnt;
	while(T --){
		int n, k;
		cin >> n >> k;
		cnt.clear();
		for(int i = 0;i < n;i++){
			int x;
			cin >> x;
			if(x % k == 0) continue;
            cnt[k - x%k] ++;
		}
		ll ans = 0;
		for(auto i :cnt){
			if(i.first == 0) continue;
			ans = max(ans, (ll)(i.second - 1) * k + i.first);
			// cout << i.first << " " << i.second << endl;
		}
        // cout<<"The ans is : ";
		if(ans)cout << ans + 1<< endl;
		else cout << ans << endl;
	}
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章