F. All Possible Digits
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
A positive number xx of length nn in base pp (2≤p≤1092≤p≤109) is written on the blackboard. The number xx is given as a sequence a1,a2,…,ana1,a2,…,an (0≤ai<p0≤ai<p) — the digits of xx in order from left to right (most significant to least significant).
Dmitry is very fond of all the digits of this number system, so he wants to see each of them at least once.
In one operation, he can:
- take any number xx written on the board, increase it by 11, and write the new value x+1x+1 on the board.
For example, p=5p=5 and x=2345x=2345.
- Initially, the board contains the digits 22, 33 and 44;
- Dmitry increases the number 23452345 by 11 and writes down the number 24052405. On the board there are digits 0,2,3,40,2,3,4;
- Dmitry increases the number 24052405 by 11 and writes down the number 24152415. Now the board contains all the digits from 00 to 44.
Your task is to determine the minimum number of operations required to make all the digits from 00 to p−1p−1 appear on the board at least once.
Input
The first line of the input contains a single integer tt (1≤t≤2⋅1031≤t≤2⋅103) — the number of test cases. The descriptions of the input test cases follow.
The first line of description of each test case contains two integers nn (1≤n≤1001≤n≤100) and pp (2≤p≤1092≤p≤109) — the length of the number and the base of the number system.
The second line of the description of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai<p0≤ai<p) — digits of xx in number system with base pp
It is guaranteed that the number xx does not contain leading zeros (that is, a1>0a1>0).
Output
For each test case print a single integer — the minimum number of operations required for Dmitry to get all the digits on the board from 00 to p−1p−1.
It can be shown that this always requires a finite number of operations.
Code
#include <bits/stdc++.h>
#define ll long long
//#define int ll
using namespace std;
const int maxn = 2e5 + 5;
int t, n, p;
void init () {}
void charming () {
init ();
scanf ("%d%d", &n, &p);
vector <int> a (n + 1);
map <int, bool> vis;
for (int i = 1; i <= n; ++i) scanf ("%d", &a[i]), vis[a[i]] = true;
int res = 0, tmp = a.back ();
bool flag = true;
for (int i = 0; i <= a[n]; ++i) if (!vis[i]) {
flag = false;
break;
}
if (flag) {
int id = -1;
for (int i = p - 1; i >= a.back (); --i) {
if (!vis[i]) {
id = i;
break;
}
}
if (id != -1) res += id - a.back ();
cout << res << endl;
return;
}
else {
res += p - a.back ();
vis[0] = true;
++a[n - 1];
int q = n - 1;
while (a[q] >= p) {
a[q - 1] += a[q] / p;
a[q] %= p;
vis[a[q]] = true;
--q;
}
vis[a[n - 1]] = true;
vis[a[q]] = true;
a[n] = 0;
}
int id = -1;
for (int i = tmp - 1; i >= 0; --i) {
if (!vis[i]) {
id = i;
break;
}
}
if (id != -1) res += id;
printf ("%d\n", res);
}
signed main () {
scanf ("%d", &t);
while (t--) charming ();
return 0;
}