Блог пользователя awoo

Автор awoo, история, 23 месяца назад, По-русски

2025A - Два экрана

Идея: BledDest

Разбор
Решение (BledDest)

2025B - Биномиальные коэффициенты, ну типа

Идея: adedalic

Разбор
Решение (adedalic)

2025C - Новая игра

Идея: fcspartakm

Разбор
Решение (awoo)

2025D - Проверка характеристик

Идея: adedalic

Разбор
Решение 1 (adedalic)
Решение 2 (adedalic)

2025E - Карточная игра

Идея: BledDest

Разбор
Решение (Neon)

2025F - Выбери свои запросы

Идея: BledDest

Разбор
Решение (BledDest)

2025G - Переменный урон

Идея: BledDest

Разбор
Решение (awoo)
  • Проголосовать: нравится
  • +77
  • Проголосовать: не нравится

»
23 месяца назад, скрыть # |
Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

Hii everyone can anyone help me D problem?

https://codeforces.me/contest/2025/my

this was my solution

i would keep count of zeros till i

then our s could range from 0 to zeros

so my state is dp[s] which will have max check passed, so my time complexity was 5000*2*10^6

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится +25 Проголосовать: не нравится

For those, who interested in combinatorial way for problem E, using something similar to Catalan numbers: I wrote a post about it

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится -10 Проголосовать: не нравится

Does Problem D fall under some Dp pattern saw this pattern of pushAndClear in many submissions it didn't click to me at all.

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

isn't the code in problem A's solution $$$ O(n^2) $$$ due to string slicing?

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

for Problem c , can anyone tell why this solution is giving wrong answer on test 4 (i used binarysearch to solve this): https://codeforces.me/contest/2025/submission/285946605 thanks in advance !!

  • »
    »
    23 месяца назад, скрыть # ^ |
     
    Проголосовать: нравится 0 Проголосовать: не нравится

    By binary research, you can only find the position of the last card which number is less than $$$(x+k-1)$$$, but you are not able to know if there are some numbers missing (between $$$x$$$ and the number of the last card). It’s the reason why you get wrong answer.

    BTW, if you choose to check through the whole interval between $$$x$$$ and $$$(x+k-1)$$$ to make sure there are no missing numbers, the time complexity would be something like $$$O(N^2)$$$ in worst case and fails the time limit.

    Therefore, I don’t think it’s possible to use binary research to solve this problem.

    • »
      »
      »
      23 месяца назад, скрыть # ^ |
       
      Проголосовать: нравится 0 Проголосовать: не нравится

      If you check my binary search function i have added this line :

      if(ss.get(m) <= (ss.get(i)+k-1) && Math.abs(ss.get(m)-m) == Math.abs(ss.get(i) -i)){
      

      here in the second part(after &&) i am checking if difference between the number and index is equal for start and end card. for ex:

      0 1 2 3 4 5 6
      3 4 5 6 8 9 10
      

      if we consider from index 1 to 3 : diff is same (4-1 == 6-3) but for index 1 to 4 : (4-1 != 8-4).

      by using this i was able to get correct answer with binary search. But on test case 4 it is failing.

      • »
        »
        »
        »
        23 месяца назад, скрыть # ^ |
         
        Проголосовать: нравится 0 Проголосовать: не нравится

        The method works only when all numbers are distinct.

        However, the problem allows number to be repeated. For example:

        (0 1 2 3 4 5)
         4 5 5 6 8 9
        

        For index 1 to 4, diff is same (8-5 == 4-1), but obviously the number 7 is missing.

        As you can see, if there are repeated numbers in the interval, the method cannot handle this situation properly.

        More precisely, if the amount of repeated numbers is same as the amount of missing numbers (while both amounts are not 0), then the result of your method would be wrong.

    • »
      »
      »
      3 недели назад, скрыть # ^ |
       
      Проголосовать: нравится 0 Проголосовать: не нравится

      We can use it, to check it we can store max difference in segtree then check that if that difference is <=1

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится +9 Проголосовать: не нравится

Problem B Binomial Coefficients Kind of Video Editorial Link: https://youtu.be/y_b2Khyk28w?si=Ku5V5m1jtT8EtA1e

»
23 месяца назад, скрыть # |
Rev. 2  
Проголосовать: нравится +12 Проголосовать: не нравится

my solution to D is a little different and it does not require bs or lazysum.

let $$$dp[i]$$$ denotes the $$$max \ score$$$ we can get if we are at index $$$j$$$ and have total $$$i$$$ intelligence points
if $$$A[i] == 0$$$ we will update dp values as follows.
let $$$cnt1[x] \ and \ cnt2[x]$$$ stores no. of checks with values x of intelligence and strength respectively.

if we choose to increase intelligence points then we are sure that we will pass all the intelligence checks having value $$$ \lt =$$$ to our current intelligence values and because all the checks with value $$$ \lt $$$ $$$current intelligence$$$ are already covered we will need to calculate how many values = current intelligence are there on the right on the right of index i and this value is stored in cnt1[current intelligence].

$$$dp[i] \ = \ max(dp[i] \ + \ cnt2[s - i], \ dp[i - 1] \ + \ cnt1[i])$$$
here $$$i$$$ is $$$current_intelligence$$$ and s is $$$current total score = intelligence + strength$$$

here is the 285916766 to explain better (ignore the code above solve function).

feel free to ask me if you have any queries. Thanks!

»
23 месяца назад, скрыть # |
Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

E can be solved using DP + OEIS sequence A050155.

Define $$$g(m,k)$$$: Number of ways to choose $$$(m+k)/2$$$ elements for Player 1 out of m cards in a given suit such that Player 1 wins as given in Problem.

Write a brute force for function $$$g$$$ -> generate the sequence and paste on OEIS -> Find the formula $$$g(m,k)$$$ given in OEIS link above -> Precompute it -> Multiply $$$g(m,j-k)$$$ with $$$DP[i-1][k]$$$ and then sum over all values of $$$0\leq k\leq j$$$ to find $$$DP[i][j].$$$ $$$1\leq i\leq n,0\leq j\leq m$$$.

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится +9 Проголосовать: не нравится

E is a typical problem that requires $$$y-x\ge k$$$ on a path from $$$(0,0)$$$ to $$$(m,n)$$$. See here for more details.

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

In Problem C, I have an issue:

I have two pieces of code. The first one:

from collections import deque
from sys import stdin
input = lambda: stdin.readline().rstrip()

def solve():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    hs = {}
    for i in a:
        if hs.get(str(i)) is None:
            hs[str(i)] = 0
        hs[str(i)] += 1
    mapLi = []
    mx = 0
    for i in hs:
        mx = max(mx, hs[i])
        mapLi.append([i, hs[i]])
    mapLi.sort(key=lambda i: (int(i[0]), -i[1]))
    ans = 0
    queue = deque([])
    cnt = 0
    for i, v in mapLi:
        ans = max(ans, cnt)
        while queue and len(queue) >= k:
            cnt -= queue.popleft()[1]
        ans = max(ans, cnt)
        while queue and abs(int(queue[-1][0]) - int(i)) > 1:
            cnt -= queue.pop()[1]
        ans = max(ans, cnt)
        queue.append((i, v))
        cnt += v
        ans = max(ans, cnt)
    ans = max(ans, cnt)
    return ans

for _ in range(int(input())):
    print(solve())

The second one:

from collections import deque
from sys import stdin
input = lambda: stdin.readline().rstrip()

def solve():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    hs = {}
    for i in a:
        if hs.get(i) is None:
            hs[i] = 0
        hs[i] += 1
    mapLi = []
    mx = 0
    for i in hs:
        mx = max(mx, hs[i])
        mapLi.append([i, hs[i]])
    mapLi.sort(key=lambda i: (int(i[0]), -i[1]))
    ans = 0
    queue = deque([])
    cnt = 0
    for i, v in mapLi:
        ans = max(ans, cnt)
        while queue and len(queue) >= k:
            cnt -= queue.popleft()[1]
        ans = max(ans, cnt)
        while queue and abs(int(queue[-1][0]) - int(i)) > 1:
            cnt -= queue.pop()[1]
        ans = max(ans, cnt)
        queue.append((i, v))
        cnt += v
        ans = max(ans, cnt)
    ans = max(ans, cnt)
    return ans

for _ in range(int(input())):
    print(solve())

I submitted the second piece of code to Codeforces Edu Round 170, Problem C, but it resulted in a Time Limit Exceeded (TLE). Then, I submitted the first piece of code, and it passed successfully. Is this an issue with the judging system, or is there a problem with my code? Can someone explain the reason? I would be very grateful!

link1:https://codeforces.me/contest/2025/submission/286123006 link2:https://codeforces.me/contest/2025/submission/286122969

If this problem is solved, you will get one of Python's optimization ticks!!!!!

  • »
    »
    23 месяца назад, скрыть # ^ |
     
    Проголосовать: нравится 0 Проголосовать: не нравится

    Avoid using dict or set in an open-hack round as they're to be easily hacked. If you have to, write your own hash function.

    By using str(i) instead of i as the key, you actually define another hash function for $$$i$$$ so you pass the test.

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится +6 Проголосовать: не нравится

Problem F is essentially equivalent to 858F - Wizard's Tour after some transformations, but I still believe it is a valuable problem for an Educational Round.

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

A $$$O(m\log m)$$$ solution for problem E. After some derivation from the editorial, we translate the question into the following form:

The cards of suit 1 need to form a bracket sequence with $$$x$$$ more open brackets, and each of the remaining suits need to form a bracket sequence with $$$a_i$$$ more close brackets, and need to guarantee $$$\sum a=x$$$.

You can see how to calculate the number of schemes in which cards of a suit have x more brackets in BLOG from darthrevenge. So we can write the generating function for a particular color:

$$$f(x)=\sum\limits_{i=0}(\binom{m}{\frac{m+k}{2}}-\binom{m}{\frac{m+k+2}{2}})x^i$$$

So the anwser is

$$$\sum\limits_{i=0}^m [x^i]f(x)[x^i]f^{n-1}(x)$$$

The only problem is to calculate

$$$f^{n-1}(x)$$$

That's a typical problem. There's two algorithm: the first is just use NTT while fast power in $O(n\log^2 n)$ and the second is use the derivation like $$$f^{m}(x)=e^{m\ln f(x)}$$$ in $$$O(n\log n)$$$. You need to calculate $$$\frac{f^m(x)}{f_0}$$$ instead of $$$f^m(x)$$$ when $$$f_0\ne 1$$$ because of $$$\ln$$$.

Submission

»
23 месяца назад, скрыть # |
Rev. 5  
Проголосовать: нравится +21 Проголосовать: не нравится

A $$$O(m\log m)$$$ solution for problem E.

From the derivation of the editorial, we can transform the question into the following form:

Cards of suit $$$1$$$ form a parenthesis sequence with $$$x$$$ extra open parentheses, and cards of suit not $$$1$$$ form a parenthesis sequence with $$$a_i$$$ extra close parentheses, $$$\sum a=x$$$.

Through the blog from darthrevenge can easily calculate a color answer. Write a generating function for a color suit:

$$$f(x)=\sum\limits_{i=0}(\binom{m}{\frac{m+i}{2}}-\binom{m}{\frac{m+i+2}{2}})x^i$$$

Then the anwser is

$$$\sum\limits_{i=0}^m [x^i]f(x)\times [x^i]f^{n-1}(x)$$$

The only problem is to calculate

$$$f^{n-1}(x)$$$

There's two ways. One is use quick power with NTT in $O(n\log^2 n)$, and the other is use $$$\ln$$$ and $$$\exp$$$ with $$$f^n(x)=e^{n\ln f(x)}$$$ in $$$O(n\log n)$$$. Notice that calculate $$$\frac{f^n(x)}{f_0}$$$ instead of $$$f^n(x)$$$ when $$$f_0\ne 1$$$ because of $$$\ln$$$. submission

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Can someone explain the formal mathematical steps for B? It's easy enough to see the breakdown into an "unweighted pascal's triangle" but can someone show formally the step from ∑i=0j(ji)⋅C[n−i][k−j] TO ∑i=0k(ki)⋅C[n−i][0] just so my mind can rest

»
23 месяца назад, скрыть # |
Rev. 2  
Проголосовать: нравится +1 Проголосовать: не нравится

"Alternate" solution to D:

We can imagine an $$$m$$$ by $$$m$$$ grid, where $$$a[i][j]$$$ represents the state of having intelligence $$$i$$$ and strength $$$j$$$. By the end, we should reach the $$$i + j = m$$$ diagonal while reaching the maximum amount of checks.

In order to get the value of a check, the following conditions must be met: $$$i \geq r$$$ (or $$$j \ge r$$$) and $$$i + j = k$$$

...where $$$k$$$ is the number of zeroes before the check. In other words, it corresponds to adding $$$1$$$ to a prefix (or a suffix) of that diagonal. This can be done using prefix sums. Code: https://codeforces.me/contest/2025/submission/285891703

It's basically the same as the model solution, just using more memory. But I feel this is more intuitive and satisfactory.

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Actually I like my D approach better — https://codeforces.me/contest/2025/submission/285910844

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится +4 Проголосовать: не нравится

Can anyone suggest DP optimisation problems similar to D?

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится +18 Проголосовать: не нравится

I have a slightly different approach for problem F, though I think it actually ends up being the same as the one explained in the editorial.

Just like the editorial, I reduce the problem to making pairs of edges. Now, notice that on tree problem is quite straightforward as you merge all the leaves of the same parent together and then destroy them. If you have some node v, with only one leaf u and parent w, make pair ((u,v), (w,v)). This guarantees optimal answer.

Now, let's say we have some additional edge a-b, that is not in the tree. We can just direct it towards a and that is identical as if we added a leaf to node a. So we will get a new tree that has Q edges and Q+1 nodes, which we can solve using the algorithm previously mentioned.

Basically, the core of the idea is that as we don't care about the nodes and just edges, we can make multiple copies of one node in order to get a tree.

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится -8 Проголосовать: не нравится

Hey can anyone help me in D, I think my TC is (m^2+n)*log(n), used dp to solve recursively and sorting checks separately between 0s, failed on test case-8 due to TLE, but saw some other solutions of same TC(I think) get all passed. Here is my code :


#include <bits/stdc++.h> using namespace std; int mod = 1e9 + 7; int main(){ int n,m; cin>>n>>m; vector<int> v(n),z; int i1 = 0; z.push_back(0); vector<vector<int>> pos(m+1); vector<vector<int>> neg(m+1); for(int i = 0; i < n; i ++) { cin>>v[i]; if(v[i] == 0) {z.push_back(i);i1++;} else if(v[i] > 0) pos[i1].push_back(v[i]); else neg[i1].push_back(abs(v[i])); } for(int i = 1; i < m+1; i ++) sort(pos[i].begin(),pos[i].end()); for(int i = 1; i < m+1; i ++) sort(neg[i].begin(),neg[i].end()); vector<vector<int>> dp(z.size()+1,vector<int>(z.size()+1,INT_MIN)); function<int(int,int)> solve = [&](int i, int j){ if(dp[i][j] != INT_MIN) return dp[i][j]; if(i == z.size()) { int tot = (lower_bound(pos[i-1].begin(),pos[i-1].end(),j+1) - pos[i-1].begin()) + (lower_bound(neg[i-1].begin(),neg[i-1].end(),i-j) - neg[i-1].begin()); return dp[i][j] = tot; } int tot = (lower_bound(pos[i-1].begin(),pos[i-1].end(),j+1) - pos[i-1].begin()) + (lower_bound(neg[i-1].begin(),neg[i-1].end(),i-j) - neg[i-1].begin()); return dp[i][j] = max(solve(i+1,j),solve(i+1,j+1)) + tot; }; int ans = solve(1,0); cout<<ans<<endl; return 0; }
»
23 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Are there any Binary Search & (non-DP) solutions to problem D?

  • I tried implementing a solution where I Binary Searched the number of points I could gain in the Intelligence Attribute. Using this, the number of points in the Strength Attribute could be found. Now by traversing the array 'r' backwards, we could decrease the Strength and Intelligence Attributes & parallelly counting the maximum score.

  • Coming to the comparison part, I compared the score to the edge cases (i.e Intelligence = m or Strength = m), If the Intelligence edge case gives a higher score, then I would try to increase the mid value in the Binary search, and if its the other way around, I would decrease the mid value in the BS.

»
23 месяца назад, скрыть # |
Rev. 3  
Проголосовать: нравится 0 Проголосовать: не нравится

I see some people getting either WA or TLE on TC-8 of problem D, using a $$$O((m^2+n) \cdot \log n)$$$ solution. I also got stuck on this during the contest, but was able to make it work afterwards: 285935817.

The issue was that my DP was storing the maximum checks for each attribute separetely (as a pair), whereas in the accepted solution I merged them into one value. Although I'm not sure why this works. If anyone has proof of why the first approach fails, I'd be interested to know.

  • »
    »
    23 месяца назад, скрыть # ^ |
     
    Проголосовать: нравится 0 Проголосовать: не нравится

    facing the same issue with 286249680

    how can i correct mine?

    appreciated!

    • »
      »
      »
      23 месяца назад, скрыть # ^ |
       
      Проголосовать: нравится 0 Проголосовать: не нравится

      Hey mate. I was looking at your code, but can't quite figure out how it works.

      One thing that I noticed is that you're using a std::map, which is cache-unfriendly and may be causing your algorithm to have a high constant factor. Could you try using a std::vector instead? In this problem it's possible because the values in the input sequence are limited by m.

      Other things you can try: avoid a second pass over the input array; eliminate the first pass over the dp array, by replacing it with a std::vector with zero-initialized values; use two one-dimensional dp vectors instead of a full matrix.

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

for problem D , please can somebody help with my dp solution

286249680

vector z => stores indices of zeros

pmp , nmp are map of long long , vector => storing indices of corresponding numbers

transition:

dp[current index of zero in z vector][positive strength]

dp[m+1][m+1]

//if pos strength is increased a = dp[I+1][pos+1] + fun(pos+1)

if negative strength be increased b = dp[I+1][pos] + fun(I — pos + 1)

here fun(x) calculates count of nos that are equal to x and ahead of index i in input

so finally dp[I][j] = max(a,b)

for me expected TC: O(m^2 * logn) . But why the tle? Also how to correct it if i am on the right track?

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится +5 Проголосовать: не нравится

dpforces

»
23 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Did anyone consider using Euler cycles/paths on problem F?

Is it possible by applying any trick to complete those components where don't exist any Euler cycle?

I just wonder, thanks in advanced.

»
23 месяца назад, скрыть # |
Rev. 4  
Проголосовать: нравится 0 Проголосовать: не нравится

**For D, An Alternative

$$$O((m^2 + n) \cdot \log N)$$$

tabulation that worked**

Let ( dp[i][j] ) denote the maximum checks passed having acquired ( i ) points and using ( j ) into intelligence, leaving ( ij ) for strength.

Now for the dp transition, we simply check if we reached this state by using the ( i )-th acquired point into strength or intelligence and binary searching for the checks passed after this.
This can be done in

$$$O( \log N)$$$

by storing the strengths and intelligence tables where the i -th element stores a vector of sorted attribute checks of the form.

My Implementation
»
23 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

In Problem F solution what is int u = v ^ qs[e][0] ^ qs[e][1] in DFS? Is this selecting random vertex for some reason?

»
22 месяца назад, скрыть # |
Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

For problem c, my approach was to form a sorted array of pair {number, frequency} using unordered_map first. Then use sliding window to keep a track of the maximumcards that i can gather. however it throws TLE on TestCase 9. I am unable to determine why is that so. Help would be appreciated here thanks!

submission link — https://codeforces.me/contest/2025/submission/287020150

  • »
    »
    22 месяца назад, скрыть # ^ |
     
    Проголосовать: нравится 0 Проголосовать: не нравится

    try using just map

    • »
      »
      »
      22 месяца назад, скрыть # ^ |
       
      Проголосовать: нравится 0 Проголосовать: не нравится

      Hey thanks, I changed unordered_map to map, and got AC. I have noticed in other problems to, where unordered_set/map gives a TLE and set/map gives AC. Is it because worst case time complexity of unordered_set/map is O(n) and for set/map it is O(log(n)) ?

      • »
        »
        »
        »
        22 месяца назад, скрыть # ^ |
         
        Проголосовать: нравится 0 Проголосовать: не нравится

        Always use map and set instead of unordered_map and unordered_set.

        Even though unordered_map and unordered_set might work during initial tests, they can fail later if someone adds a large test case that triggers their worst-case performance, which is O(n). This can cause your solution to be too slow and get a "Time Limit Exceeded" error.

        map and set are more reliable because they guarantee O(log(n)) performance.

»
22 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Spoiler

»
22 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Spoiler

»
22 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Spoiler

»
21 месяц назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Another approach for Problem D: https://codeforces.me/contest/2025/submission/294067890

Hints:

--> when we hit a 0, we either increase strength or intelligence
        both strength and intelligence can be solved independenty and similarly
--> let say if we can pass a strength check of value sC then we can pass all strength check of values <=sC
--> let say current strength is sC, and we increase it by 1, sC = sC +1
--> then all the strength checks witth value sC +1 can be passed on the right.
     */
»
5 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

有人帮我c题吗?第10个答案错误

»
4 месяца назад, скрыть # |
 
Проголосовать: нравится -15 Проголосовать: не нравится

I made an other solve of E, based on basic dp, that counts amount of CBS with len i and balance j https://codeforces.me/contest/2025/submission/371918386