思路 :
對於一個數 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"usingnamespace std;#define mem(a,b) memset(a,b,sizeof(a))#define pb push_backtypedeflonglong ll;constint maxn =1e4+7;constint INF =INT_MAX;constdouble EPS =10;// #define _DEBUGintmain(){#ifdef _DEBUGfreopen("./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;}return0;}