Idea: vovuh

**Tutorial**

Tutorial is loading...

**Solution (vovuh)**

```
for i in range(int(input())):
n, k = map(int, input().split())
print('YES' if k * k <= n and n % 2 == k % 2 else 'NO')
```

1327B - Princesses and Princes

Idea: BledDest

**Tutorial**

Tutorial is loading...

**Solution (pikmike)**

```
from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
used = [False for i in range(n)]
v = -1
for i in range(n):
l = [int(x) - 1 for x in stdin.readline().split()][1:]
for j in l:
if not used[j]:
used[j] = True
break
else:
v = i
if v == -1:
stdout.write("OPTIMAL\n")
else:
u = used.index(False)
stdout.write("IMPROVE\n" + str(v + 1) + " " + str(u + 1) + "\n")
```

Idea: Neon

**Tutorial**

Tutorial is loading...

**Solution (Ne0n25)**

```
n, m, _ = map(int, input().split())
print(2 * (n - 1) + (n + 1) * (m - 1))
print("U" * (n - 1) + "L" * (m - 1), end="")
for i in range(n):
if i != 0:
print("D", end="")
if i % 2 == 0:
print("R" * (m - 1), end="")
else:
print("L" * (m - 1), end="")
```

Idea: adedalic

**Tutorial**

Tutorial is loading...

**Solution (adedalic)**

```
#include<bits/stdc++.h>
using namespace std;
#define fore(i, l, r) for(int i = int(l); i < int(r); i++)
#define sz(a) int((a).size())
#define x first
#define y second
typedef long long li;
typedef pair<int, int> pt;
const int INF = int(1e9);
const li INF64 = li(1e18);
int n;
vector<int> p, c;
inline bool read() {
if(!(cin >> n))
return false;
p.resize(n);
c.resize(n);
fore(i, 0, n) {
cin >> p[i];
p[i]--;
}
fore(i, 0, n)
cin >> c[i];
return true;
}
inline void solve() {
vector<int> used(n, 0);
int ans = INF;
fore(st, 0, n) {
if(used[st])
continue;
vector<int> cycle;
int v = st;
while(!used[v]) {
used[v] = 1;
cycle.push_back(v);
v = p[v];
}
fore(step, 1, sz(cycle) + 1) {
if(sz(cycle) % step != 0)
continue;
fore(s, 0, step) {
bool eq = true;
for(int pos = s; pos + step < sz(cycle); pos += step) {
if(c[cycle[pos]] != c[cycle[pos + step]])
eq = false;
}
if(eq) {
ans = min(ans, step);
break;
}
}
}
}
cout << ans << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
int tt = clock();
#endif
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cout << fixed << setprecision(15);
int tc; cin >> tc;
while(tc--) {
read();
solve();
#ifdef _DEBUG
cerr << "TIME = " << clock() - tt << endl;
tt = clock();
#endif
}
return 0;
}
```

Idea: adedalic

**Tutorial**

Tutorial is loading...

**Solution (Roms)**

```
MOD = 998244353
p = [1] * 200005
for i in range(1, 200005):
p[i] = (p[i - 1] * 10) % MOD
n = int(input())
for i in range(1, n):
res = 2 * 10 * 9 * p[n - i - 1]
res += (n - 1 - i) * 10 * 9 * 9 * p[n - i - 2]
print(res % MOD, end = ' ')
print(10)
```

Idea: Neon

**Tutorial**

Tutorial is loading...

**Solution (Ne0n25)**

```
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define sz(a) int((a).size())
#define all(a) (a).begin(), (a).end()
#define forn(i, n) for (int i = 0; i < int(n); ++i)
typedef pair<int, int> pt;
const int MOD = 998244353;
const int N = 500 * 1000 + 13;
int n, k, m;
pair<pt, int> q[N];
int ones[N];
int mx[N], sum[N];
int add(int x, int y) {
x += y;
if (x >= MOD) x -= MOD;
if (x < 0) x += MOD;
return x;
}
int calc(int t) {
memset(ones, 0, sizeof(ones));
memset(mx, -1, sizeof(mx));
forn(i, m) {
int l = q[i].x.x, r = q[i].x.y;
if (q[i].y & (1 << t)) {
ones[l]++;
ones[r + 1]--;
} else {
mx[r] = max(mx[r], l);
}
}
int j = -1;
forn(i, n) {
int cur = 0;
if (!ones[i]) {
cur = sum[i];
if (j == -1) cur = add(cur, 1);
else cur = add(cur, -sum[j]);
}
sum[i + 1] = add(sum[i], cur);
ones[i + 1] += ones[i];
j = max(j, mx[i]);
}
return add(sum[n], j != -1 ? -sum[j] : 1);
}
int main() {
scanf("%d%d%d", &n, &k, &m);
forn(i, m) {
scanf("%d%d%d", &q[i].x.x, &q[i].x.y, &q[i].y);
--q[i].x.x; --q[i].x.y;
}
int ans = 1;
forn(i, k) ans = (ans * 1ll * calc(i)) % MOD;
printf("%d\n", ans);
}
```

1327G - Letters and Question Marks

Idea: BledDest

**Tutorial**

Tutorial is loading...

**Solution (BledDest)**

```
#include<bits/stdc++.h>
using namespace std;
const int N = 8000043;
const int K = 15;
const int M = 1043;
int k;
char buf[N], buf2[M];
vector<string> t;
vector<int> c;
string s;
map<char, int> nxt[M];
int lnk[M];
int p[M];
char pchar[M];
map<char, int> go[M];
int term[M];
int ts = 1;
int A[M][K];
int F[M][K];
int dp[M];
int get_nxt(int x, char c)
{
if(!nxt[x].count(c))
{
p[ts] = x;
pchar[ts] = c;
nxt[x][c] = ts++;
}
return nxt[x][c];
}
void add_string(int i)
{
int cur = 0;
for(auto x : t[i])
{
cur = get_nxt(cur, x);
}
term[cur] += c[i];
}
int get_go(int x, char c);
int get_lnk(int x)
{
if(lnk[x] != -1)
return lnk[x];
if(x == 0 || p[x] == 0)
return lnk[x] = 0;
return lnk[x] = get_go(get_lnk(p[x]), pchar[x]);
}
int get_dp(int x)
{
if(dp[x] != -1)
return dp[x];
dp[x] = term[x];
if(get_lnk(x) != x)
dp[x] += get_dp(get_lnk(x));
return dp[x];
}
int get_go(int x, char c)
{
if(go[x].count(c))
return go[x][c];
if(nxt[x].count(c))
return go[x][c] = nxt[x][c];
if(x == 0)
return go[x][c] = 0;
return go[x][c] = get_go(get_lnk(x), c);
}
void build_skip(const string& s, vector<int>& sA, vector<long long>& sF)
{
sA = vector<int>(ts);
for(int i = 0; i < ts; i++)
sA[i] = i;
sF = vector<long long>(ts);
for(auto c : s)
{
int ci = int(c - 'a');
for(int i = 0; i < ts; i++)
{
sF[i] += F[sA[i]][ci];
sA[i] = A[sA[i]][ci];
}
}
}
long long solve(const string& s)
{
long long BAD = (long long)(-1e18);
vector<int> pos;
for(int i = 0; i < s.size(); i++)
if(s[i] == '?')
pos.push_back(i);
int cntQ = pos.size();
vector<vector<int> > skip_A(cntQ + 1);
vector<vector<long long> > skip_F(cntQ + 1);
build_skip(s.substr(0, pos[0]), skip_A[0], skip_F[0]);
for(int i = 1; i < cntQ; i++)
build_skip(s.substr(pos[i - 1] + 1, pos[i] - pos[i - 1] - 1), skip_A[i], skip_F[i]);
build_skip(s.substr(pos.back() + 1, s.size() - pos.back() - 1), skip_A[cntQ], skip_F[cntQ]);
vector<vector<long long> > dp(1 << (K - 1), vector<long long>(ts, BAD));
vector<int> used(1 << K);
dp[0][skip_A[0][0]] = skip_F[0][0];
queue<int> q;
q.push(0);
used[0] = 1;
long long ans = BAD;
while(!q.empty())
{
int k = q.front();
q.pop();
int step = __builtin_popcount(k);
if(step == cntQ)
{
for(int i = 0; i < ts; i++)
ans = max(ans, dp[k][i]);
continue;
}
for(int i = 0; i < K - 1; i++)
{
if(k & (1 << i)) continue;
int nk = (k ^ (1 << i));
if(used[nk] == 0)
{
used[nk] = 1;
q.push(nk);
}
for(int j = 0; j < ts; j++)
{
if(dp[k][j] == BAD)
continue;
int nj = get_go(j, char('a' + i));
int newSt = skip_A[step + 1][nj];
long long add = get_dp(nj) + skip_F[step + 1][nj];
dp[nk][newSt] = max(dp[nk][newSt], dp[k][j] + add);
}
}
}
return ans;
}
int main()
{
scanf("%d", &k);
t.resize(k);
c.resize(k);
for(int i = 0; i < k; i++)
{
scanf("%s %d", buf2, &c[i]);
t[i] = buf2;
}
scanf("%s", buf);
s = buf;
for(int i = 0; i < k; i++)
add_string(i);
for(int i = 0; i < ts; i++)
{
lnk[i] = -1;
dp[i] = -1;
}
for(int i = 0; i < ts; i++)
{
get_lnk(i);
for(char c = 'a'; c <= 'o'; c++)
get_go(i, c);
}
for(int i = 0; i < ts; i++)
get_dp(i);
for(int i = 0; i < ts; i++)
{
for(int j = 0; j < K; j++)
{
A[i][j] = get_go(i, char('a' + j));
F[i][j] = dp[A[i][j]];
}
}
int n = s.size();
vector<int> leftQ(n, -1);
vector<int> rightQ(n, -1);
for(int i = 0; i < n; i++)
{
if(i != 0)
leftQ[i] = leftQ[i - 1];
if(s[i] == '?')
leftQ[i] = i;
}
for(int i = n - 1; i >= 0; i--)
{
if(i != n - 1)
rightQ[i] = rightQ[i + 1];
if(s[i] == '?')
rightQ[i] = i;
}
vector<int> bad(n, 0);
if(leftQ.back() == -1)
bad = vector<int>(n, 1);
long long ans = 0;
int curSt = 0;
string news = "";
for(int i = 0; i < n; i++)
{
int ci = (s[i] == '?' ? 14 : int(s[i] - 'a'));
if(bad[i])
ans += F[curSt][ci];
curSt = A[curSt][ci];
if(!bad[i])
news.push_back(s[i]);
else if(i != 0 && !bad[i - 1])
news.push_back('o');
}
if(!news.empty())
ans += solve(news);
printf("%lld\n", ans);
}
```

D and E should have been swapped !

Great Contest! Congratulations!

In this contest Problem A is also very tricky.

For E i used a more dp like solution.

The number of blocks of size n is allways 10. Let

$$$bl(n)=10$$$

$$$bl(n-1) = 2*10^2 - 10*2 = 180$$$

$$$bl(n-2) = 3*10^3 - 180*2 - 10*3$$$

$$$bl(n-3) = 4*10^4 - bl(n-2)*2 - 180*3 - 10*4$$$

$$$bl(n-4) = 5*10^5 - bl(n-3)*2 - bl(n-2)*3 - bl(n-1)*4 - bl(n)*5$$$

...

This can be implemented in $$$O(n)$$$ with simple additions and multiplications. 74112302 (I use pow there, but that could be a multiplication, too)

What's the logic behind this? I found this pattern but it didn't make sense to me.

Thanks in advance.

For say n=3 there are $$$3*10^3$$$ single digits. But some of those digits have neighbours which are same digit, we call them blocks.

So, every digit not belonging to a block is a single digit. For n=3 this is $$$3000 - 2*180 - 3*10$$$ The 2 and 3 are the size of the blocks, 180 and 10 are the number of blocks.

And that pattern repeats, since for any blocksize, if n is increased by one, the number of blocksize+1 is the same as before. Every block can be extended by one member.

The reason for the pattern is that the total number of digits is always going to be n * 10^n, so you're just weighting each block count by its size and finding the value for the next n that makes it add up to the right value.

Why total number of digits is always n*(10^n)? Shouldn't it be 10^n only? Thanks.

It is $$$10^n$$$ numbers, $$$n$$$ digits each.

RHS of bl(n-i) contains n-i terms hence a total computation of summation i over n which is quadratic. Is this what you mean?

I solved this problem in the same way. You can maintain the value that you are subtracting off, and update as you go. if value[] is the value you want, psum[] is the partial sum of value[], and subs[] is the amount you are subtracting off, then the transitions are:

subs[i] = subs[i+1] + psum[i+2] + 2*value[i+1]

value[i] = (n-i+1) * 10^(n-i+1) — subs[i]

psum[i] = psum[i+1] + value[i]

There are other ways to do it, but this is how I did it in my code. 74286577

I like this implementation.

How can you implement this in o(n)?

Wont it take o(n^2)?

I'm leaving the power part, just for to demonstrate how to do it in O(N)$$$bl(n - x) = bl(n - x + 1)*2 + bl(n - x + 2)*3 + ... + bl(n + x - x)*(x+1)$$$

$$$bl(n - (x + 1)) = bl(n - (x + 1) + 1)*2 + bl(n - (x + 1) + 2)*3 + ... + bl(n - (x + 1) + (x + 1)) *((x + 1)+1)$$$

The second equation can be written as.

2.$$$bl(n - (x + 1)) = bl(n - x)*2 + \left[bl(n - x + 1)*3 + ... + bl(n) *(x+2)\right]$$$

And the first.

The difference is:

$$$sum = bl(n - x + 1) + bl(n - x + 2) + ... + bl(n) $$$

$$$bl(n - (x + 1)) = bl(n - x)*2 + sum + bl(n - x)$$$

So we just have to update $$$sum$$$ each step.

For me, this is bit annoying than the solution described in the tutorialCan you please explain why for n=3 b(1) = 2610? I think it must be 2700 -> 10*9*10*3

It is $$$3*10^3=3000$$$ single digits. There are 3 blocksizes, 1, 2 and 3. So, 3000-bl(3)-bl(2)==bl(1)

bl(3)=10 obviously (000,111,222,...,999)

bl(2)=180, since 9*00x, 9*11x,..., 9*x00,9*x11,...,9*x99

3000-180*2-10*3=2610

Note that the number of digits and number of blocks is the same for bl(1), since each block has size=1.

Can anyone explain the solution of D with examples and the topic I must know before solving it?

You should read about Cyclic Permutations to understand this topic better.

Ok thank you ^_^

Can someone explain solution of E? The language in the editorial is very hard to follow for me.

especially "blocks which first element is a first element of integer"

For E , consider we are finding answer for length k , let x be the number within block ( 0 <= x <=9) for say k=3 and n=7; then two cases are : 1. xxx++++ , ++++xxx 2. +xxx+++ , ++xxx++ , +++xxx+ these are ( n — k -1 ) For case a: u choose x in 10 ways , now immediate next to x has to be different because we are doing this for length k ,so it will be chosen in 9 ways , remaining we have ( n-k-1)positions left which can be filled with 10 numbers . For case b : u can understand similarly .

How can we be guaranteed that there are no collisions, like For n==5 and k==2 Case:1 00___ -> last two dashes have 10 chances each so 00_00 is possible. ___00 -> first two dashes have 10 chances each so 00_00 is possible. We are counting that twice write.but we are not supposed to be.

yeah , i thought about that and this is the reason i could not solve in the contest , i too thought that there will be collision . But this is not a collision , we actually need to add these two . Just take some time , u will see . ( we need block count , focus on this ). See , for 00x** , counting the right x** gives u numbers which contains it and it implies this block was present in them . for , **x00 we do the same and this block was present in them . When we add these two values , we are adding blocks 00___ and ___00 and 2 different block because of their position . For eg , 00900 u need to do +2 and not +1 .

thanks man its nice to observe this thing For eg , 00900 u need to do +2 and not +1(block count). thanks

Take the example of

n=5, k=2where n is the total size, and k is the block size. So .33.. and ...99 would fall under this.ObservationsCalculations(Edit: Just realized that the editorial pretty also goes into detail — I had not read that for E. So may be worth referencing that as well.)

Cool, Thanks! I understand the solution however it feels that at my current level it is very unlikely that i ll be able to come up with a solution like this :(

Not at all. I'm sure you can do it with practice. I didn't get this during the contest either. But I had an improvement over the last few times when I had similar problems (when I was completely clueless). This time at least I was approximately right as I was close to a solution. The only difference between then and now has been doing some practice on paper.

It will look a lot simpler when you do it on paper, than by reading and trying to comprehend. Use this text as reference and don't get overwhelmed by it.

How can we be guaranteed that there are no collisions, like For n==5 and k==2 Case:1 00___ -> last two dashes have 10 chances each so 00_00 is possible. ___00 -> first two dashes have 10 chances each so 00_00 is possible. We are counting that twice write.but we are not supposed to be.

The problem asks for blocks, not how many unique numbers match the criteria. A hint in that direction is the second example: when n = 2, and k = 1, you'd expect 90 numbers, but the answer is 180, since it is blocks. A block is simply the same digit repeated to a certain length. So the number 23 would have 2 blocks of size 1 in it, even though it is only one number.

Note that if you were to calculate the count of unique numbers, instead of blocks, then you'd divide this by a certain factor (your example correctly identifies the overcounting that needs to be accounted for).

thanks dude , little bit confused with blocks and numbers,finally understood.

Here check out my video solution https://www.youtube.com/watch?v=gmis4iWP_pY

Could someone explain the time complexity for problem D?

$$$O(n^{1/3})$$$ is a "rule of thumb" approximation for $$$\max _{x=1} ^{n} d(x)$$$, the maximum number of divisors of $$$x \in [1,n]$$$. For exact values, you may consult this list.

Theoretically, this formula is $$$O(n^\epsilon)$$$ for any $$$\epsilon > 0$$$, but it takes very large values of $$$n$$$ to converge, so this fact's not useful in typical competitive programming contexts.

You can get a close approximation at typical CP-relevant ranges ($$$n \lesssim 10^{18}$$$) via the formula $$$\max _{x=1} ^{n} d(x) \approx \min (3.5273 n^{1/3}, n^{1.066 / \ln \ln n})$$$ (source)

can you explain the 3rd test case of problem D. i`m getting ans with p5 but how for p2

Q

8 7 4 5 6 1 8 3 2 5 3 6 4 7 5 8 4

solution In the third test case, p2=[3,6,1,8,7,2,5,4] and the sequence starting from 4: 4,p2[4]=8,p2[8]=4,… is an infinite path since c4=c8=4.

For each index, you need to build the cycle for that index (and mark the other members of the cycle in an auxiliary array so you don't build any cycle more than once). Then for each divisor $$$d$$$ of the cycle size $$$s$$$, you want to find a position $$$i$$$ where all indices $$$cycle[i + kd]$$$ for $$$k \in [0, \frac s d)$$$ have the same color. A success means you have found a path in $$$p^d$$$, so the smallest $$$d$$$ of all successes is the answer.

Sample: 74200072

Can you please explain why the paths in a cycle are coming periodically for any divisor D of that cycle length and are not arbitrarily? For a divisor like 2 for length 6 — the paths are like (1, 3, 5) and (2, 4, 6), why are they periodic?

By drawing some examples I can see the pattern but is there any proof for this?

Due to Bézout's identity, if a cycle has a suitable "infinite path" of period $$$k$$$ that doesn't divide $$$m$$$, it also has one of period $$$\gcd (k, m)$$$, which is $$$< k$$$ and does divide $$$m$$$.

For D, example 2 of the problem statement states:

`In the second test case, p5=[1,2,3,4,5] and it obviously contains several infinite paths.`

However, if you take the original array p1 = [2 3 4 5 1], and run through the iterations, then:

So is there an issue with the statement, or in the way p5 has been calculated?

$$$p^k[i]$$$ isn't calculated from $$$p^{k-1} [p^{k-1} [i]]$$$

It is $$$p^k[i] =p[p^{k-1}[i]]$$$

It was mentioned in the problem that multiplications like c=a*b turns out to be like c[i] = b[a[i]]

So $$$p^k=p^{k-1}*p$$$ turns out to be $$$p[p^{k-1}[i]]$$$

Clear now. Thank you very much.

In Problem D, if t=1 , n=3 , p[]=[ 2, 3, 3 ] , c[]=[ 2, 1, 3 ]. As we already have an infinite cycle at p[3] of length 2. So output must be 1. But above code of awoo is giving 3. So, please point out my mistake, if any.

elements of the permutation are unique. It's mentioned in the problem "The second line contains n integers p1,p2,…,pn (1≤pi≤n, pi≠pj for i≠j) — the permutation p."

Oh, Sorry I didnt notice it. Thanks for the reply

no probs :)

the array p[] is a permutation of 1 to n , it can't have 2 3 3

I should have noticed it :) Thanks for the reply

I think this contest was prepared very well. Especially solutions of C and E were satisfying. Thanks to authors.

Can this editorial be linked to the contest? Thanks!

Why is the time complexity for problem B O(n + m), what is m as mentioned in the editorial? Shouldn't it be O(n^2), because k can be any value up to n.

Yes, k can be any value up to N but. You didn't read the guaranteed carefully as there is a line told that.

It's also guaranteed that the total number of kingdoms in lists over all test cases does not exceed 10^5.

So if you run through all K. it's only up to 10^5 for all test cases. You can think M as the total number of kingdoms in lists.

PROBLEM A can someone explain the condition : if(n%2!=k%2) then "NO"

thanks

Odd+Odd=Even.

Even+Odd=Odd.

Therefore you can only make N from sums of K odd number if and only if they have the same parity.

For the problem G, there needs little effort to reduce the complexity from $$$O(L |S|)$$$ to $$$O(m L^2 + |S|)$$$. Who is interested can compare my two submissions 74205780 and 74200846.

stO 叉姐 Orz, can you explain the details? thanks a lot!

Divide the string $$$s$$$ with questions marks into $$$(m + 1)$$$ parts $$$p_0, p_1, \dots, p_m$$$. Essentially, we need $$$\mathrm{go}(u, p_i)$$$ for each node $$$u$$$ in the Aho-Corasick Automaton and its corresponding contribution. Direct computation leads to $$$O(L |S|)$$$ as the editorial says. However, if $$$p_i > L$$$, all $$$\mathrm{go}(u, p_i)$$$ agree on the value. Thus, we need only compute $$$\mathrm{go}(u, p_i)$$$ for one $$$u$$$.

wow, thank you! I just realized I used the same technique on a contest I prepared last year(

You mean if $$$|p_i| > L$$$ then the value gained by traversing the substring $$$p_i$$$ in the A-C automaton is the same regardless of the initial state? I cannot see why this is true. Please elaborate on this. Thanks!

Let's elaborate a bit. Suppose that $$$p_i > L$$$ and $$$p_i = ab$$$ where $$$|a| = L$$$. We will see that $$$\mathrm{go}(u, a) = v$$$ is a constant regardless of the $$$u$$$. Thus, the contribution can be separated into two pieces: the one from $$$u$$$ to $$$v$$$, which can be computed in time $$$O(|L|^2)$$$, and the one starting from $$$v$$$, which can be done in time $$$O(|b|)$$$.

Thank you every much, I think I understand it now. The idea is that if we think of a node $$$u$$$ of the AC automaton as the corresponding string, then $$$\mathsf{go}(u, p_i)$$$ will arrive at some suffix of the string $$$up_i$$$ and when $$$p_i$$$ is long enough, that suffix will be solely part of $$$p_i$$$. Correct me if I'm wrong.

The use of c both as a permutation and the colour function makes it confusing at times.

In Problem D, if t=1 , n=3 , p[]=[ 2, 3, 3 ] , c[]=[ 2, 1, 3 ]. As we already have an infinite cycle at p[3] of length 2. So output must be 1. But above code of awoo is giving 3. So, please point out my mistake, if any.

The p[] array must consist of disinct elements .

But in your test case 2nd and 3rd elements are both 3 .

Oh sorry , i didnt notice that :) Thank for replying

Who can help me explain F clearly! Thanks!

See my comment

Can someone help me in the solution for problem D. I got the question but the editorial is hard to follow. Thanks in advance!

The D question demands lot of observations and tricks . Read The editorial line by line just as hints and try them yourself . I assure that may help a lot

I did it over and over, still not able to catch up. Can you help me by providing some relevant prerequisites or a dry run of the solution?

I can't understand the DP defination of problem F. Would anyone explain for it clearly? Thanks.

First note that we can calculate a result for each bit separately and multiply them all for the final answer. Iterate $$$s$$$ over $$$[0, k)$$$, and let $$$b_i$$$ represent the bit in position $$$s$$$ of $$$x_i$$$.

We can now divide the conditions into what we'll call $$$1$$$-segments and $$$0$$$-segments in accordance to its $$$b_i$$$ for the current $$$s$$$.

Note that most of our arrays and data structures we use should be indexed over $$$[0, n+1]$$$ (we'll see why in a moment). The $$$[l, r]$$$ in the conditions should remain 1-indexed.

Now we do the precalculation step. We want two things from the precalculation:

For each index, we want to know whether it is covered by a $$$1$$$-segment. This is a classic "union of segments" problem and can be done in many ways: pre-sorting and two pointers, removal from sorted sets, or even DSU

For each index $$$i$$$, we want to know the maximum $$$l$$$ among all $$$0$$$-segments whose $$$r < i$$$. If you're stuck, see the spoiler for details on how to do this efficiently. We'll call these values $$$f_i$$$ in accordance with the editorial. (If no such segments exist for index $$$i$$$, $$$f_i = 0$$$.)

SpoilerFirst initialize all $$$f_i$$$ to $$$0$$$. For each $$$0$$$-segment, set $$$f_{r+1} \leftarrow \max (f_{r+1}, l)$$$. Then iterating over $$$[1, n+1]$$$, set $$$f_i \leftarrow \max (f_i, f_{i-1})$$$

We can now perform the DP. $$$dp_i$$$ represents the number of arrays of length $$$i$$$ that end with a $$$0$$$, and all $$$0$$$-segments contained within it contain at least one $$$0$$$.

$$$dp_0$$$ represents the empty array and therefore should be $$$1$$$.

Now we iterate $$$i$$$ over $$$[1, n+1]$$$

If $$$i$$$ is covered by a $$$1$$$-segment, $$$dp_i = 0$$$ as we can't place a $$$0$$$ in this position.

Otherwise $$$\displaystyle dp_i = \sum_{j = f_i}^{i-1} dp_j$$$ because the last-seen zero cannot be in a position earlier than $$$f_i$$$. This can be calculated efficiently by maintaining a prefix sum over $$$dp$$$.

The result for bit $$$s$$$ is equal to $$$dp_{n+1}$$$. This is because we can always fix a $$$0$$$ at the fictitious $$$n+1$$$-th index, and delete it to get a suitable array.

Asymptotics $$$\tilde{O}(k(n + m))$$$ with a possible $$$\log$$$ factor somewhere depending on implementation. Bonus: Solve in strict $$$O(k(n + m))$$$.

sample: 74254156 (uses a specialized DSU-like data structure for the union-of-segments problem)

What about the segments which are neither in 0-segment nor in 1-segment?

It's fine. Because you've already precalculated $$$f_i$$$, if there are no constraints on the index, $$$f$$$ would not increase and the summation will continue accumulating.

Thank you so much!

I'm finding it bit hard to understand why $$$dp_{i}=\sum_{j=f_{i}}^{i-1}dp_{j}$$$. Can you please explain.

$$$dp_j$$$ counts the set of strings that are length $$$j$$$ and end with a zero. So for each of those strings, you are able to add ones until index $$$i-1$$$, and then add a zero to form part of $$$dp_i$$$'s set.

For D, I can see why it holds that on raising by power m it divides into gcd(m,L) cycles (L=lenth of original cycle) but why does it hold when m does not divide L? Can someone give intuition/mathematical reason for this? I can see that it holds but why?

when

`gcd(m,L) = 1`

`L*x%m = 0`

only when x == m,essentially you have to walk through every single element in the cycle until you return to c1 because all mutiples of L mod m should be distinctelse assume

`x and y are integers < m and x>y`

then if`Lx%m = Ly%m`

,then`(x-y)L%m = 0`

which is a contradiction since gcd(L,m) = 1 and x-y < mI spent some time looking at D and wanted to improve upon the given solution with external resources.

Notice that P is nothing more than a cyclic permutation. Lecture notes on Permutation Groups and Symmetric groups. Each permutation can be written in Disjoint cycle notation. Thus there exists cycles.

let A = (a1 a2 a3 .. am) be a cycle. then A^k can be written in Disjoint cycle notation with gcd(k, m) cycles each of cycle length m / gcd(k, m). Proof

So let us look at all cycles A = (a1 a2 ... am). We need to take a look at all subcycles of length x. This corresponds to every cycle when we raise A to k. since x = gcd(k, m) from 2, x | m. Thus we can skip a lot of values of x.

If a particular answer of x has the property that all colors in it are same then ans = min (ans, x).

Why min(ans, x) ans not min(ans, k)? 1. We don't know exact k that it would have been raised to. 2. Notice gcd(k1, m) == gcd(k2, m) => same cycle[properties of cyclic group] Thus x is the least value of k such that gcd(m, k) = x as x | m.

in the editorial,it was stated that The

`for k1 and k2 such that GCD(k1,m)=GCD(k2,m) the produced cycles will have the same sets of vertices and differ only in the order of walking`

although this should seem intuitive given your second statement that`let A = (a1 a2 a3 .. am) be a cycle. then A^k can be written in Disjoint cycle notation with gcd(k, m) cycles each of cycle length m / gcd(k, m)`

but is there a concrete way to prove itThe best proof I found was from math stack exchange. But I can provide a quick intuition of why there are gcd(k, m) cycles. 1. A = (a1 a2 .. am-1 am) has |A| (order) = m. Then |A^k| = m / gcd(m, k). This is a property of cyclic groups, and the current group is <A>.

um,i think you misunderstood my question,i understand why there should be gcd(k,m) disjoint cycles of m/gcd(m,k) length.i was asking about why

`for k1 and k2 such that GCD(k1,m)=GCD(k2,m) the produced cycles will have the same sets of vertices and differ only in the order of walking`

,why is this true and why cant there be two different cycles(different set of vertices) with the same starting pointOh sorry yeah i misunderstood you. It turns out that <A^k> = <A^gcd(m, k)>. Thus if Gcd (m, k1 == gcd(m, k2) then they result in the same subgroup. note <a> is the subgroup generated by a

ah,thank you,i think i got it now

Can anybody explain problem A.I couldn't understand the editorial.

So basically , there are only 2 cases in which the output can be "No" , ones where the parity of n and k is different because odd number of odd numbers can only add upto an odd number and similarly for 2n odd numbers .

And the second case where we get NO as a result will be when the sum of first k odd numbers exceeds n. Understand this as if the minimum of the k odd numbers (that is the first k odd numbers) add up to be more than k , then there is no way to choose k numbers such that there sum=n.

example: 7 3 here ist 3 odd numbers , i.e 1+3+5 = 9 , so there is no way we can hava a solution for this case.

Also it is important that the k odd numbers should be distinct.

can someone explain me how in A, that parity being equal and k^2<=n be the only two conditions we need to check?

sum of odd numbers when their quantity is even leads to even no while when quantity is odd it leads to odd no. eg- 1+3=4(qty=2 and sum is even), 1+3+5=9(qty=3(odd) and sum is odd)

sum of first k odd natural number is k*k. So min sum is k*k. n should always be greater than k*k

I am still not able to understand the implementation of problem E .Please someone explain me in a easier way.

here check out my video solution https://www.youtube.com/watch?v=gmis4iWP_pY

In Q1327B can there be more than one ans?(for test case 2) eg- IMPROVED 1 1 or IMPROVED 2 1

In the editerial for problem D, "for k1 and k2 such that GCD(k1,m)=GCD(k2,m) the produced cycles will have the same sets of vertices and differ only in the order of walking", I can vaguely understand it, but who can prove it rigorously? why "the same sets of vertices"?

Suppose, you have the cycle $$$c_0, c_1, \dots, c_{m-1}$$$. Since $$$p^k[c_i] = c_{(i + k) \mod m}$$$, then $$$c_i$$$ and $$$c_j$$$ will be on the same split up cycle iff $$$i + kx \equiv j \mod m$$$ or $$$i + kx - my = j$$$ or $$$j - i = kx - my$$$.

There is a property that all solutions of $$$kx \pm my$$$ with an integer $$$x$$$ and $$$y$$$ is divisible by $$$GCD(k, m)$$$, so it means that $$$i - j$$$ is divisible by $$$GCD(k, m)$$$.

Finally, since $$$GCD(k_1, m) = GCD(k_2, m)$$$ then it's obvious that the same pairs of indices will be on the same split up cycles.

Problem E: Why don't we count the same blocks a couple of times in the first case? When we multiply 10 * 9 * 10^(n — len — 1), there are some cases included when the right side is also a block with the same length, and then we count that twice by multiplying 2.

Here check out my video solution https://www.youtube.com/watch?v=gmis4iWP_pY

Can someone help me with a TLE on problem G? I'm struggling to determine if my time complexity is the problem or if I just need to reduce my constant factor. It looks like a lot of the other solutions are using bfs to compute the subproblems (I'm using recursion) but I'm not sure what the benefit of that approach is. Here's my submission 74512969.

edit: problem was that I was using LONG_MIN instead of LLONG_MIN...

Uploaded solution videos for A-E on this link.

https://www.youtube.com/playlist?list=PLl4Y2XuUavmuDC4ZST4F_peD1jO_xvVfW

Can anyone plz explain howz the number of cycles is Size/gcd(size,k) in D

Here is my analysis (had to read multiple comments and the editorial to arrive at this).

Now ($$$p^k[c_i] = c_{(i+k)mod m}$$$) :

this is similar to jumping k steps at a time. Now each sub-cycle will be produced by starting at

i(for simplicity taking ($$$c_i$$$) as i), and then after jumpingk stepsforxno. of times we will reach back ati. This completes our sub-cycle i.e. ($$$i + kx \equiv i mod m$$$) wherexas you can see is the no. of jumps taken to reach back at i, also is the length of this sub-cycle.Or, ($$$i + kx - my = i \implies kx = my$$$) for some integer y.

Now to find the min. x such that above equation holds, you see k and m are fixed, so kx = my = lcm(k, m). And as we know lcm(k, m) = km/gcd(k, m) = km/g.

Therefore, ($$$x = lcm(k, m)/k \implies x = km/kg \implies x = m/g$$$). Hence proved length, x of sub-cycle produced is

size/gcd(size, k).Now to prove that no. of subcycle will be gcd(k, m):

you can see that each sub-cycle will of equal size, starting with some i, j, ... , also each element has to be a part of exactly 1 such subcycle, thus product of no. of subcycles and size of each such subcycle must be 'm', hence the proof follows.

For proof of second observation as per editorial, please refer adedalic comment.

Hope this helps :)

It helped me a lot to understand! Thank you!

In the tutorial of problem G, could someone explain why the dp can be done in O(K*L*2^K) instead of O(L*K^2*2^K)? We need to iterate the character we take in this '?', so there is an additional K in the complexity.

UPD: maybe the amount of ? (14) is ignored as a constant. The complexity seems too high to get AC in 4secs.

UPD again: I had just got aware that the number of statu is O(L*2^K), so this works.

I found it difficult to understand the editorial and the solution for F. I spent a lot of time to understand it. Therefore I wrote a well commented solution. Hope it helps.

Commented CodeIn B, why this test case is Optimal?

Test Case1

5

1 1

1 2

1 3

2 3 4

3 3 4 5

Can't we add 5 to the 4th daughter? (What I misunderstood?)

Its already optimal all 5 daughters get matched already, so you cant improve any further. 1 -> 1 2 -> 2 3 -> 3 4 -> 4 5 -> 5

No point of improving

problem E was straightforward

Just find f(n) — 10f(n-1) , this gives a pattern

Try it yourselff(2) — 10f(1) = 80

f(3) — 10f(2) = 810

f(4) — 10f(3) = 8100

f(5) — 10f(4) = 81000

f(6) — 10f(5) = 810000

and

so on ...