awoo's blog

By awoo, history, 6 years ago, translation, In English

1009A - Game Shopping

Tutorial
Solution (Vovuh)

1009B - Minimum Ternary String

Tutorial
Solution (Vovuh)

1009C - Annoying Present

Tutorial
Solution (PikMike)

1009D - Relatively Prime Graph

Tutorial
Solution (PikMike)

1009E - Intercity Travelling

Tutorial
Solution (BledDest)

1009F - Dominant Indices

Tutorial
Solution (BledDest)

1009G - Allowed Letters

Tutorial
Solution (Bleddest)
  • Vote: I like it
  • +69
  • Vote: I do not like it

| Write comment?
»
6 years ago, # |
  Vote: I like it +8 Vote: I do not like it

How did you got that diff_i formulae in E?

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +27 Vote: I do not like it

    Suppose there is a rest site right before the kilometer we are trying to cross. The probability of this is 0.5 (and then we get a1 as the difficulty).

    Ok, suppose then there is no rest site at position i - 1, but it is at position i - 2. The probability of this is 0.25, and then we get a2 as the difficulty.

    Then we consider the option when there is a rest site at position i - 3, but no rest sites at position i - 2 and i - 1. The probability of this is 0.125, the difficulty is a3.

    And so on, until we get to position 0.

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it +2 Vote: I do not like it

      Roger that ^_^

    • »
      »
      »
      2 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      In the solution code the cur is calculated by multiplying a[i] with power of 2. But in the tutorial it was a[i]multiplied by 1/power of 2. Can you please explain this?

      Also I didn't understand the last line of the tutorial where diff[i+1] was derived with the help of diff[i]. Thank you very much.

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Is there a reason for bounds on F to be 10^6 instead of something a bit smaller like 2*10^5? The problem ended up being pretty hard to solve in Java even with the intended solution. I understand not wanting more naive solutions to pass though.

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +8 Vote: I do not like it

    Probably to disallow the solution with euler tour and sqrt-decomposition.

  • »
    »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    why would a linear solution fail? maybe you lost time in reading input just like me.

    • »
      »
      »
      6 years ago, # ^ |
      Rev. 2   Vote: I like it -8 Vote: I do not like it

      Java is about 5x slower than C++, so many times, perfectly fine solutions in C++ fail in java. I've had java solutions fail many times because I was using long instead of int, or an arraylist/customdatastructure instead of an array, or recursion instead of iteration. I've also gotten accepted verdicts by rewriting slow java code in c++.

      Though you can lose time reading input with scanner, there are many other ways to lose time, ways that C++ or even python uses don't need to care about. I don't think any accepted solutions in java for this problem used recursion, but many did in C++.

      Case and point: When I made this comment, there were 25 accepted c++ solutions and 6 TLE c++ solutions. Java had 36 TLE solutions (from 6 distinct people) and only 10 accepted solutions (from 6 distinct people).

»
6 years ago, # |
Rev. 2   Vote: I like it +3 Vote: I do not like it

As mentioned by Redux on Announcement page, problem D can be solved by using recurrence relation such that if (a,b) is a co-prime pair then (2a - b, a), (2a + b, a) and (a + 2b, b) are also co-prime where a > b.

Base cases are (2, 1) for even-odd pairs and (3, 1) for odd-odd pairs. The list is also exhaustive as mentioned in this link so there is no overlapping also. The only breaking condition will be a > n or when m co-prime pairs are stored.

In this way, we will always jump to only co-prime pairs rather than checking every other pair.

So time complexity will also be much less than one given in editorial (Correct me if I am wrong).

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +8 Vote: I do not like it

    Lets say you check that m>=n-1 and phi(2)+...+phi(n)>=m. The probability of gcd being 1 is O(1) so we can randomly generate edges and check if gcd is 1. If we use map complexity will be: O(n+mlogm). But one can also prove that without randomizatiom complexity is O(n+m).

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      We don't need to check phi sum as one can just store the pairs and if the no. of pairs are less than m, then it is impossible.

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Problem G is almost same as the problem Poetic Word from ACM-ICPC Amritapuri Regionals 2017.

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +20 Vote: I do not like it

    Is it, really?

    Yes, the main idea of solution is similar, but checking if we can build the suffix when n = 200 and when n = 105 is, I suppose, "a bit" different.

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Yeah, the main idea is the same. The difference is in the way to optimize it and using the fact that the alphabet size is small to create less number of nodes by using masks.

»
6 years ago, # |
Rev. 2   Vote: I like it -8 Vote: I do not like it

My solution 40344721 for problem E. I think it's easier

#include <cstdio>
#include <vector>
using namespace std;
typedef long long int ll;
const ll mod = 998244353;
int main()
{
	ll pow2 = 1, p=0, curp;
	int n;
	scanf("%d", &n);
	vector<ll> cost(n);
	for (int i = n-1; i >= 0; i--) scanf("%lld", &cost[i]);
	p += cost[0];
	for (int i = 1; i < n; i++) {
		curp = (pow2*(i + 2)) % mod;
		curp = (curp*cost[i])%mod;
		p = (p + curp) % mod;
		pow2 = (pow2 * 2) % mod;
	}
	printf("%lld", p);
	return 0;
}
  • »
    »
    6 years ago, # ^ |
      Vote: I like it -8 Vote: I do not like it

    I also use this method.

    But I don't know how to prove that

    • »
      »
      »
      6 years ago, # ^ |
      Rev. 4   Vote: I like it -8 Vote: I do not like it

      Sequence from https://oeis.org/A001792.

      My proof: (n-segment means segment of length n).

      a[i] = 1, 3, 8, 20, 48 ... a[0] = 1, because a n-segment can be paved with a n-segment in one way. a[i] is equal the number of ways to pave the free parts of the n-segment for all possible positions of the segment of length >= n-i. (statement 1)

      System: a[0] = 1 a[i] = a[i-1]+2*2^(i-1) + Σ 2^(k-1)*2^(i-k-1) (from k=1 to i-1) = a[i-1]+(i+3)*2^(i-2), for every i>=1.

      Clarification: a[i-1] — because we count for all segments of length >=n-i.

      2*2^(i-1) is equal the number of ways to pave the free parts in case 1 in pic.

      Σ 2^(k-1)*2^(i-k-1) (from k=1 to i-1) is equal the number of ways to pave the free parts in case of movement (n-i)segment, where 2^(k-1) — left part, 2^(i-k-1) — right part. (case 2 in pic)

      Proof of "The number of ways to pave the n-segment by k segments is ((n-1)!/(k-1)!)/(n-k)!" you can find here http://kvant.mccme.ru/pdf/1999/05/kv0599levin.pdf after 11-task (it is on russian lang, but i cant find this in english). The number of ways to pave the n-segment by different segment is sum and equals 2^(n-1).

      Sorry for my bad english, i used google translate.

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it -8 Vote: I do not like it

      Sorry, i forgot to attach the pic

      • »
        »
        »
        »
        6 years ago, # ^ |
        Rev. 3   Vote: I like it -8 Vote: I do not like it

        I got a more intuitive prove!

        define F(n,k) as number of distance notless than k. So the final result is Σ(k=1~n) F(n,k)*ak.

        F(n,n) = 1

        F(n,n-1) = 3

        F(n,n-2) = 8

        F(n,n-3) = 20

        ...

        It's easy to see that F(n,k) = F(n-x,k-x) when k>x.

        F(1,1) = F(n,n) = 1

        F(2,1) = F(n,n-1) = 3

        F(3,1) = F(n,n-2) = 8

        F(4,1) = F(n,n-3) = 20

        ...

        So, rewrite the result as Σ(k=1~n) F(k,1) * ak

        F(1,1) =1

        for F(k,1) , we calculate F(k+1,1): insert a new gap 1' between 0 and 1, it can be a stop , or not stop, and this covers all situations,

        if the 1' is a stop, it contribute F(k,1) + 2^k , 2^k from 0 to 1', the others remain F(k,1)

        if the 1' is not a stop, it contribute F(k,1) also, because, F(k,1) means count all gap nums, insert a nonstop don't change the gap nums.

        Together we get F(k+1,1) = F(k,1)*2 + 2^k.

        ✿✿ヽ(°▽°)ノ✿

»
6 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

What does " "pull" our depth arrays upwards" means? Thanks in advance..

  • »
    »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Assume that u is a child of v and the depth array of u is d[u] = [1, 2, 2]

    You want to create the depth array for v (d[v] = {1, 1, 2, 2]), but without creating it from scratch (which would take O(n) time).

    Using maps instead of arrays allows to do this in time, and using vectors with the reversed depth arrays allows doing it in even O(1).

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      In the add method of struct state, if (*a)[i] == (*a)[cur_max] then don't we need the min(i, cur_max) as dominant index according to given conditions? Thanks in advance..

      • »
        »
        »
        »
        6 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Yes, but he did compared also the index with pairs, so this case is already included in the editorial solution.

        • »
          »
          »
          »
          »
          6 years ago, # ^ |
          Rev. 2   Vote: I like it 0 Vote: I do not like it

          In the add method we are comparing pairs (val_at_i, i) and (val_at_cur_max, cur_max), if both the values are same then we are updating cur_max if i > cur_max. If the values are same we want to change the value of cur_max only if i < cur_max according to given conditions. Did I miss something?

          • »
            »
            »
            »
            »
            »
            6 years ago, # ^ |
              Vote: I like it +3 Vote: I do not like it

            His depth vector is reversed.

            • »
              »
              »
              »
              »
              »
              »
              6 years ago, # ^ |
                Vote: I like it 0 Vote: I do not like it

              Ohh.. thanks for replying, got my mistake

            • »
              »
              »
              »
              »
              »
              »
              6 years ago, # ^ |
              Rev. 3   Vote: I like it -8 Vote: I do not like it

              code In this solution of problem F,he is just forming depth array of all the nodes in the form of array of maps ,and using the factor of logn ,pulling up the maps and merging smaller into bigger at all stages ,but why is he not getting MLE ....as if tree is linear,then space would be O(n^2) UPD:GOT IT.....EVERY TIME WE MERGE PARENT AND ITS CHILD ,WE ARE SWAPPING THEIR MAPS(IF SMALLER) AND THEN MERGE,SO SIZE OF PARENT INCREASES AND ITS CHILD DECREASES....

»
6 years ago, # |
  Vote: I like it +5 Vote: I do not like it

Problem G , author's solution . We can just rebuild the graph with brute force and run dinic on it .

This could pass all tests if we do not use vector .

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +8 Vote: I do not like it

    I tried your idea, and it worked :) I used vectors though, if you were interested in it, you may have a peek: Submission 40553125.

    I suppose that if the alphabet size was 7 then this approach would've been to slow (graph would have about 140 edges) while Authors' solution will fit in the limits.

    Thank you for your comment and best regards :)

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Wow,you have very nice optimize technique !

      This is my solution

      Which I got TLE*7 before :)

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I have a question about the memory complexity of F: since every node's memory is its max "height", when the tree becomes a chain,it will rise to n(n+1)/2, And I can't run the data on my computer,so I wonder if it will get MLE

  • »
    »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    If the tree is a chain, I believe you will actually only have 1 (mutable) array. All the nodes will point to that same array. Each time you go up the tree you just copy that array and add 1 to it. This works since you never need to use arrays lower down in the tree again

»
6 years ago, # |
  Vote: I like it -7 Vote: I do not like it

I am a little confused by the D solution given in the tutorial.In my opinion the O(N^2*log⁡(N)) is not going to fit in time because, as i know the time formula = TimeComplexity(MAXN)/10^9 which is O(N^2*log(N))/10^9 and converting N to MAXN(10^5) is (10^5)^2*log(10^5)/10^9 seconds, 10^10*16/10^9 = 160 seconds. Correct me if i am wrong(i am 100% wrong but i would like an explanation why). As i know from my little experience a O(N^2) solution for a TimeLimit of 2 second a MAXN of 10^5 is way to big.

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    The program in this case terminates much faster because only at n = 600, we already get M >= 100000.

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

For problem F, first example, why is the output 3 2 1 0 wrong? There may be several dominant indices for given node, right?

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    No,dominant index needs to have largest frequency and as closest as possible to the parent node

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    The problem is asking for the minimum index of the maximum element in the array. Therefore, there is only 1 dominant index.

    The array of vertex 1 is: [1, 1, 1, 1, 0, ...] => answer is 0. The array of vertex 2 is: [1, 1, 1, 0, ...] => answer is 0. The array of vertex 3 is: [1, 1, 0, ...] => answer is 0. The array of vertex 4 is: [1, 0, ...] => answer is 0.

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

For problem 1009 D, how is it sufficient to prove that graph has m valid edges in order to make sure that graph is connected? (Like what I can't get is when is the program making sure that graph that it prints is "connected"?)

  • »
    »
    6 years ago, # ^ |
    Rev. 2   Vote: I like it +6 Vote: I do not like it

    It isn't sufficient, you need to do both checks.

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      The graph which program prints is connected, right? But how can we say that?

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    In the line, forn(i, n) for (int j = i + 1; j < n; ++j), we are making sure that the graph we built is connected because in the very first loop when i = 0, we are connecting the vertex 1 with all other vertices for j = 1 to n-1, thus making it a connected graph.

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    1 is coprime of all numbers, hence in the first iteration itself(if m>=n-1) you are making the graph connected.

»
6 years ago, # |
  Vote: I like it -8 Vote: I do not like it

In this hacked solution, I used long double for the answer, and added up the intermediate means. The editorial says 10 byte float will pass. So, how many bytes does long double uses? 8? If so, how can we use a 10 byte or larger float in C++? I know I could've done this by first calculating sum using long long int, but just want to know out of curosity, it may help in some future contests. Thanks :)

»
6 years ago, # |
  Vote: I like it -8 Vote: I do not like it

My submission for E: http://codeforces.me/contest/1009/submission/40471843 Can someone tell me where the overflow is happenning and how to fix it?

  • »
    »
    6 years ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    There's a subtraction in line 26, and if it could be negative, you have to consider it becomes negative. If your procedure is correct, you may fix it by adding mod in line 26.
    In C++11 or above, modulo (by using '%') for negative integer, it will be negative integer from (1-mod) to 0.

    (But sadly, I checked your solution with simple fix got TLE. And finally, I cannot remove TLE... My solution is calculating 2^n every time (and this method is slower than yours) but got AC, so I think the cause of TLE is twice multiplication in loop... Sorry for failing to get AC. Someone, please help!)

    My AC sol : https://codeforces.me/contest/1009/submission/40479814

    My submission for checking (removed WA, but TLE) : https://codeforces.me/contest/1009/submission/40481944

    EDIT : I had to say the cause of WA of your original submission is not overflow.

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      ai is always positive. Since diff[i] is sum of ai divided by positive numbers(2^n), it is also always positive. So I don't understand what could be negative and why we should add mod. Also where are taking mod for a negative integer, the minus sign is outside the multiplication?

      • »
        »
        »
        »
        6 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        On modulo, increasing numbers cannot be always increasing numbers. For example, [10, 20, 30] mod 11 is [10, 9, 8]. Similary, (ai * 2^(n-i)) > (ai * 2^(n- i-1)) is true on integer, but not always true on modulo.

        • »
          »
          »
          »
          »
          6 years ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          Understood. Then shouldn't we multiply by -1? By adding mod we will get something else right?

          • »
            »
            »
            »
            »
            »
            6 years ago, # ^ |
              Vote: I like it 0 Vote: I do not like it

            You can multiply negative numbers, and also subtract, divide(if mod is prime).
            When the number is negative, add mod and you can get right value.
            And more, considering the value is big or already positive, you can write like this.

            ans = (ans % mod + mod) % mod;

            I often write something like this!

            • »
              »
              »
              »
              »
              »
              »
              6 years ago, # ^ |
                Vote: I like it +5 Vote: I do not like it

              Understood what you're saying. Thanks for being patient!!!

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    (nested deeply, so I wrote here)

    I finally got AC by fixing your submission!

    https://codeforces.me/contest/1009/submission/40486361

    I added this.

    ios::sync_with_stdio(false), cin.tie(0);

    Just with this, the TLE is removed.

    Note that if there are many inputs, you must write it or use only scanf and printf. It is faster!

    good luck!

»
6 years ago, # |
  Vote: I like it -20 Vote: I do not like it

Problem B : I never understood this line.Even till now

String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i ( 1 ≤ i ≤ | a | , where | s | is the length of the string s ) such that for every j < i holds a [j] = b [j] , and a [i] < b [i] .

What is string a ans string b, and indices i and j. What I understood was that string a is the output, and string b is the input string..!!!`` I cant get the relation between editorial explanation with the above statement given in the question. Help me pls regards ;)

  • »
    »
    6 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    String a is lexicographically less than string b if the person with name a is earlier in a phone book than the person with name b.

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      ok.... thanks for your answer... :)

      so it means in their world, there are only alphabets {0,1,2} 0 < 1 < 2 in the order. i got that. But the conditions : i < j and a[j] = b[j].... and a[i] < b[i].

      i/p : 100210

      o/p : 001120

      what is i and j in this case .... ? Regards :)

»
6 years ago, # |
  Vote: I like it -8 Vote: I do not like it

40500124,(AC),40499958,(MLE)

For the problem 1009F's solution, and in the Struct state, why i used "vector a" and got the MLE while i used "vector *a" and got the AC? Thanks in advance...

»
6 years ago, # |
Rev. 5   Vote: I like it 0 Vote: I do not like it

I would like to share another approach to solve D, though it runs slower and harder to code. (Sorry for the poor English beforehand.)

Let rp[i] be a set storing all j <= n, such that gcd(i, j) = 1.
When constructing rp[i], we can count total number of pair (i, j) such that j > i and j is in rp[i], and terminate when this number >= m.
It is clear that the total number of found numbers won't exceed 2m + n when we stop.

The basic case, rp[1], is all integers in [1, n].
To construct rp[i], first we pick maximum prime factor p (can be found by sieve) of i, "remove" it from i. Formally, let i = p1k1 * p2k2 * ... * pzkz * pk, pi are primes, then we calculate the value temp = p1k1 * p2k2 * ... * pzkz, it can be found in O(logpn) by dividing i by p while i % p == 0.

Since gcd(i, j) = 1 if and only if (i, j) share no common prime factor, we have
rp[i] = rp[temp]  -  set of all numbers in rp[temp] which has prime factor p.

We can simply iterate through rp[temp] from small to large, when we found a number x, check whether it can be divided by p, and add it to rp[i] if it cannot.

By doing so, we may fail (found a number x but doesn't add it to rp[i]) many times, but for at most O(logpn) failures there must be one success (add x to rp[i]) before all those failures, because when we fail for some x = p1k1 * p2k2 * ... * pzkz * pk, we must have add y = p1k1 * p2k2 * ... * pzkz to rp[i] before. Since x <= n, k can only be numbers picked from [1, floor(logpn)], thus each success corresponds to at most O(logpn) failures.

Because p must be greater than 2, and success always comes before failures, this algorithm runs in O((n + m) * log2n).

Here is my submission

Please correct me if I am wrong.

  • »
    »
    6 years ago, # ^ |
    Rev. 4   Vote: I like it 0 Vote: I do not like it

    UPD.

    I am stupid, simply let temp = i / p and the arguments still hold.

    UPD2.

    Also we can store j only for j > i and gcd(i, j) = 1 in rp[i]. The number of operations is smaller than or equal to the previous one.

    submission

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Question 1009C: Annoying Present
I am getting a relative error = '0.0000206' in test case 9. I am using a double type variable to store the mean values for each new transformation. I have no clue how to reduce the error for the result. My code is here : https://codeforces.me/contest/1009/submission/40511515.
Any help is appreciated.

  • »
    »
    6 years ago, # ^ |
    Rev. 3   Vote: I like it 0 Vote: I do not like it

    Every single floating point operation causes precision error. Try to replace them by integer operations as many as possible.

    For example, you can sum up all x by integer operations, and add it to mean at last. In this way we use just a single floating point operation rather than O(m) floating point operations, therefore the precision error can be reduced.

    The same trick can also be applied to d.

»
6 years ago, # |
Rev. 2   Vote: I like it -19 Vote: I do not like it

My solution for Prob.E. Maybe it's better??

#include <cstdio>
#include <cstring>
#include <iostream>
#define P 998244353
using namespace std;

typedef long long LL;
LL n, a[1000005], ans, p = 1;

int main()
{
	scanf("%I64d", &n);
	for(int i = 1; i <= n; i++)
		scanf("%I64d", a + i);
	for(int i = n - 1; i > 0; p = (p << 1) % P, i--)
		ans = (ans + (n + 2 - i) * p % P * a[i] % P) % P;
	printf("%I64d\n", (ans + a[n]) % P);
	
	return 0;
}//Rhein_E

One Way to prove this:

»
6 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

my solution of F says Stack Overflow can someone suggest me some way to manage it on Test 131

»
6 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Can anyone give a more intuitive explanation to the solution of problem G? I understand what's being done, but not why it's being done. Such as why are we decreasing the flows in the path and stuff.

»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Another (probably harder) way to solve E: We need to consider all possible partitions of a sequence of length N. We know that each chunk of length X in each partiton will add prefix_sum(X) to the answer, so we need to calculate number of chunks of length X for all possible Xs in all possible partitions. This is https://oeis.org/A045623 . There are a lot of different formulas to caluclate this (but I don't know how to derive them to be honest).

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Can anyone tell me why I got wa in first solution but ac in second solution in problem C?The difference between these two is the variable type.

first solution:https://ideone.com/qEkY5S

second solution:https://ideone.com/vuRdGW

»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

In the solution code the cur is calculated by multiplying a[i] with power of 2. But in the tutorial it was a[i]multiplied by 1/power of 2. Can anyone please explain this?

Also I didn't understand the last line of the tutorial where diff[i+1] was derived with the help of diff[i].

»
17 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Why O(N2LOGN) is fast enough in D? i need explanation

»
7 months ago, # |
  Vote: I like it 0 Vote: I do not like it

G can be solve within a better Time complexity O(A^2n)。

It can be viewed here(In Chinese)

Code:

#include<bits/stdc++.h>
using namespace std;
// #define int long long
const int maxn=1e5+5;
int cur[maxn],sze[6],n,m,alo[maxn][7],vis[6],can[6];
char s[maxn];
unordered_set<int> d[6][6];
#define VI vector<int>
VI cur;
bool dfs(int u,int t){
	if(u==t)return 1;
	vis[u]=1;
	for(int i=0;i<6;i++){
		if(vis[i])continue;
		if(d[u][i].size()){
			cur.push_back(i);
			if(dfs(i,t))return 1;
			cur.pop_back();
		}
	}
	return 0;
}
void DFS(int u){
	can[u]=1;
	for(int i=0;i<6;i++){
		if(can[i])continue;
		if(d[u][i].size())DFS(i);
	}
}
VI findpath(int u,int v){
	cur={u};
	for(int i=0;i<6;i++)vis[i]=0;
	if(dfs(u,v))return cur;
	return {};
} 
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin>>s+1;n=strlen(s+1);
	cin>>m;
	for(int i=1;i<=m;i++){
		int k;string s2;
		cin>>k>>s2;
		for(auto u:s2)alo[k][u-'a']=1;
		alo[k][6]=1;
	}
	for(int i=1;i<=n;i++){
		if(!alo[i][6])for(int j=0;j<6;j++)alo[i][j]=1;
	}
	for(int i=1;i<=n;i++)sze[s[i]-'a']++;
	for(int i=n;i>=1;i--){
		bool flg=0;
		for(int j=0;j<6;j++){
			if(!alo[i][j])continue;
			if(sze[j]){
				sze[j]--;cur[i]=j;
				for(int k=0;k<6;k++)if(alo[i][k]&&j!=k)d[j][k].insert(i);
				flg=1;break;
			}
			VI F;
			for(int k=0;k<6;k++)can[k]=0;
			DFS(j);
			for(int k=0;k<6;k++){
				if(j!=k&&sze[k]&&can[k]&&alo[i][k]){
					F=findpath(j,k);
					int t[7];
					for(int i=0;i<F.size()-1;i++)t[i]=(*d[F[i]][F[i+1]].begin()),sze[F[i]]++,sze[F[i+1]]--;
					for(int i=0;i<F.size()-1;i++){
						cur[t[i]]=F[i+1];
						for(int l=0;l<6;l++)if(alo[t[i]][l]&&l!=F[i+1])d[F[i+1]][l].insert(t[i]);
						for(int l=0;l<6;l++)if(alo[t[i]][l]&&l!=F[i])d[F[i]][l].erase(t[i]);
					}
					sze[k]--;
					cur[i]=k;
					for(int l=0;l<6;l++)if(alo[i][l]&&l!=k)d[k][l].insert(i);
					flg=1;
					break;
				}
			}
			if(flg)break;
		}
		if(!flg)return cout<<-1<<endl,0;
	}
	for(int i=1;i<=n;i++){
		for(int j=0;j<6;j++)if(alo[i][j]&&j!=cur[i])d[cur[i]][j].erase(i);
		int res=-1;
		DFS(cur[i]);
		for(int j=0;j<cur[i];j++){
			if(!alo[i][j]||!can[j])continue;
			VI F=findpath(cur[i],j);
			int t[7];
			for(int i=0;i<F.size()-1;i++)t[i]=(*d[F[i]][F[i+1]].begin());
			for(int i=0;i<F.size()-1;i++){
				cur[t[i]]=F[i+1];
				for(int l=0;l<6;l++)if(alo[t[i]][l]&&l!=F[i+1])d[F[i+1]][l].insert(t[i]);
				for(int l=0;l<6;l++)if(alo[t[i]][l]&&l!=F[i])d[F[i]][l].erase(t[i]);
			}
			res=j;
			break;
		}
		if(res==-1)res=cur[i];
		cur[i]=res;
		cout<<res+'a';
		for(int j=0;j<6;j++)if(alo[i][j]&&j!=cur[i])d[cur[i]][j].insert(i);
	}
	return 0;
}