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

Автор vovuh, история, 4 года назад, перевод, По-русски

1454A - Особая перестановка

Идея: MikeMirzayanov

Разбор
Решение

1454B - Unique Bid Auction

Идея: MikeMirzayanov

Разбор
Решение

1454C - Изменение последовательности

Идея: MikeMirzayanov

Разбор
Решение

1454D - Число в последовательность

Идея: MikeMirzayanov

Разбор
Решение

1454E - Количество простых путей

Идея: vovuh

Разбор
Решение

1454F - Разделение массива

Идея: MikeMirzayanov

Разбор
Решение
Решение (Gassa)
Разбор задач Codeforces Round 686 (Div. 3)
  • Проголосовать: нравится
  • +134
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится +39 Проголосовать: не нравится

Really liked problem E, great contest.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

great problems, thanks Mike and vovuh for setting div. 3s! much appreciated.

»
4 года назад, # |
  Проголосовать: нравится +14 Проголосовать: не нравится

did i get bonus point by succefully hacking someones code in this div3 contest? P.S : i am new in this codeforces platform

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +13 Проголосовать: не нравится

    No. Bonus point can only be earned in regular Div.1 and Div.2 Round, or some Div.1+Div.2 Round like Global Round.

»
4 года назад, # |
  Проголосовать: нравится +40 Проголосовать: не нравится

The leaf trick for E is really neat , really liked it ... Nice contest

  • »
    »
    4 года назад, # ^ |
    Rev. 2   Проголосовать: нравится +9 Проголосовать: не нравится

    Can you pls explain how would you implement the straight-forward solution which is: "just extract and mark all cycle vertices and run dfs from every vertex of a cycle"? Thanks

    • »
      »
      »
      4 года назад, # ^ |
        Проголосовать: нравится +9 Проголосовать: не нравится

      Start a dfs from any vertex and maintain prev of each element i.e the node before that node in the dfs tree. Now when you come across a visited vertex $$$v$$$ from the vertex $$$u$$$, then this means this vertex $$$v$$$ is part of a cycle and the cycle is $$$v, prev[v], prev[prev[v]], ... , u$$$.

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

        won't going to prev everytime take you to the root ? i guess you need to find the first common ancestor of u and v

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

        Can you explain which vertices are the cycle vertices?And what does it mean by "trees hanged on cycle vertices". I am not clearly understanding the solution to E.

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

          Since the graph is connected and number of vertices is equal of number of edges, there will a only one cycle. Now you can notice other vertices will form a trees with cycles vertices as roots. (Try drawing some pictures)

    • »
      »
      »
      4 года назад, # ^ |
        Проголосовать: нравится +18 Проголосовать: не нравится

      Consider storing the graph as vector <set <int> >, each vertex having a set of edges to adjacent vertices. Then we can efficiently remove an edge from the graph, by just removing it from the sets at both ends. In fact, here is a solution that does just that: 99510704

    • »
      »
      »
      4 года назад, # ^ |
      Rev. 6   Проголосовать: нравится +3 Проголосовать: не нравится

      I implemented it but can't find my mistake

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

    can you explain leaf trick bit more i didnt get that??

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

      since the graph contains n edges that means it is a tree with one extra edge. This one extra edge will create some cycle in the tree. Now any note the following point 1) Any node in this cycle is of atleast degree 2 2) observe leaf trick -> we are picking the leaf nodes one by one and removing them and the edge between it and it's parent after processing. And after this removal either the parent node could either be of degree 1 (a new leaf), or (some node with more descendents present which would eventually be removed by the leaf trick). Or this parent node could be in the cycle. after removal of all the children nodes only nodes present in the cycle will be left in the queue.

»
4 года назад, # |
Rev. 4   Проголосовать: нравится +8 Проголосовать: не нравится

Can anyone tell me, in problem F's solution provided by Gassa: In the expansion part, "we can pick the side of expansion after which the value min(u,v,w) is larger, and if these are equal, pick any". I can't understand why in the case of equal, we can pick any. Wouldn't that affect afterwards?

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

    We can prove that if there is an answer, this approach won't lose it.

    Assume the maximum on left segment is $$$u$$$, the minimum on middle segment is $$$v$$$, the maximum on right segment is $$$w$$$ and there exists a partition makes $$$u = v = w = x$$$.

    For all the second segments that satisfy the condition, there is a biggest one include all the others, let it be $$$[L, R]$$$. (Easy to see if another segment $$$[L', R']$$$ also makes $$$u = v = w = x$$$ and neither of them includes the other, $$$[min(L, L'), max(R, R')]$$$ will be the one includes them both.)

    Because after every move $$$min(u, v, w)$$$ will only be smaller or stay the same, and $$$[L, R]$$$ is the biggest segment makes $$$u = v = w = x$$$. So for a partition $$$[l, r]$$$, if $$$l < L$$$ or $$$r > R$$$, $$$min(u, v, w) < x$$$. (Otherwise $$$[l, R]$$$ also satisfy the condition and it's bigger than $$$[L, R]$$$.)

    Initially, $$$[l, r]$$$ is included by $$$[L, R]$$$. When will we lose the answer? Only when $$$l = L$$$ and we make $$$l$$$ decrease or vice versa. But if we do so, $$$min(u, v, w)$$$ will be smaller than $$$x$$$ as we mentioned above, but in the other choice $$$min(u, v, w) >= x$$$, so the algorithm will pick the other and will not lose the answer.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can someone tell me what's wrong in my code for Problem D

My Code
»
4 года назад, # |
Rev. 4   Проголосовать: нравится +8 Проголосовать: не нравится

I have a simple approach for F:

(to avoid misunderstanding, I will count the array from index 1)

First, we will create an array $$$left$$$ and $$$right$$$ satisfy these condition:

a) $$$1 \leq left_i \leq i \leq right_i \leq n$$$

b) $$$A_i = min(A_{left_i}, A_{left_{i + 1}}, A_{left_{i + 2}}, ..., A_{right_i})$$$

c) $$$right_i - left_i$$$ is maximum.

We can build this array using deque, as I indicated in my submission.

Then, we will try to find out two index $$$x$$$ and $$$y$$$ such that $$$x \geq left_i - 1$$$ and $$$y \leq right_i + 1$$$. (why?).

To find out $$$x$$$ and $$$y$$$, we will maintain 2 more arrays: prefix maximum and suffix maximum. And the rest part could be done easily with binary search.

Finally, we can partition the initial array into 3 parts: $$$x$$$, $$$y - x - 1$$$, and $$$n - y + 1$$$.

My submission: 99517001

»
4 года назад, # |
  Проголосовать: нравится -47 Проголосовать: не нравится

can anyone help me why my B question do not get accepted although my idea was same but failed particular testcase ~~~~~``

include<bits/stdc++.h>

using namespace std; typedef long long ll; typedef std::vector vi;; typedef pair<ll, ll> pi;

define ull unsigned long long

define F first

define S second

define PB push_back

define MP make_pair

define boht_tez ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)

define MAXN ll(1e5 + 123)

define MAXINP ll (1e3 + 123)

define MAX_SIZE 100000000

int main() {

ifndef ONLINE_JUDGE

// for getting input from input.txt
freopen("input1.txt", "r", stdin);
// for writing output to output.txt
freopen("output2.txt", "w", stdout);

endif

ll t;
cin >> t;
while (t--) {

    ll n;
    cin >> n;
    ll a[n];
    ll b[n] = {0};
    ll mx = 0;

    for (ll i = 0; i < n; i++) {
       cin >> a[i];



       b[a[i]]++;


       mx = max(a[i], mx);
    }

    bool flag = true;
    ll g;
    for (ll i = 1; i <= mx; i++) {
       if (b[i] == 1) {

         flag = false;
         g = i;
         break;
       }

    }
    if (n == 1) {
       cout << 1 << "\n";
    }
    else if (n == 2) {
       if (a[0] == a[1]) {
         cout << -1 << "\n";
       }
       else if (a[0] > a[1]) {
         cout << 2 << "\n";
       }
       else if (a[0] < a[1]) {
         cout << 1 << "\n";
       }
    }
    else if (flag == true) {
       cout << -1 << "\n";
    }
    else {
       for (ll i = 0; i < n; i++) {
         if (a[i] == g) {
          cout << i + 1 << "\n";
          break;
         }
       }
    }

}

}

~~~~~

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +4 Проголосовать: не нравится

    u know right, You will get downvoted for pasting code rather than posting the submission link?

    • »
      »
      »
      4 года назад, # ^ |
        Проголосовать: нравится +20 Проголосовать: не нравится

      sorry this was first time i tried to interact in editorials...next time i will keep in mind ..my bad

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

Anyone help me where i am getting wrong for problem F 99476252 or is my logic incorrect?

UPD: got AC (just because i wrote log() inplace of log2()).

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can anybody explain why my solution https://codeforces.me/contest/1454/submission/99483191 for D is giving TLE

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

    i*i <= n causes integer overflow and leads to increased iterations of the for loop. Changing int to long long should work.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

can someone explain problem 2 in detail??

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

    You have to print the index of the minimum element of all the elements that occur only once in the given array. Hope this makes it clearer.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can anyone familiar with C++ please explain this, In the editorial of Problem C, std::unique returns a forward iterator to the end of the modified vector right? Are we typecasting that to an int here ?

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +8 Проголосовать: не нравится

    We are getting the size of the array after modification, i. e. removing consecutive duplicates. As vector iterator is a random access iterator, so we can just subtract vector::begin(), to get the total number of elements from the beginning of vector to the end of the modified vector

»
4 года назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

is E solvable for more than n edges?

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Why system testing happens in Contests having open hacking phase , meaning it shows Accepted then what is the need of system testing

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +1 Проголосовать: не нравится

    It is rejudged with hack cases. If someone's solution gets hacked, the author decides if he wants to include the hack case (i think) and everyone's code is tested again.

»
4 года назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

my solution for question 2 is same as written in tutorial, but it was hacked , Why :( solution link https://codeforces.me/contest/1454/submission/99428157

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

    Maybe you get TLE because for each test you are resetting arrays flag and ind to 0. Thus the time complexity is $$$O(4 * 10 ^ 9) = ~4s$$$.

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

      if i use vector insted of array ,i got ac?

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

        No it's not that. Just at the first for don't go through all the elements. Go through the first n+1 and it will be fine.

        • »
          »
          »
          »
          »
          4 года назад, # ^ |
            Проголосовать: нравится +3 Проголосовать: не нравится
          for(int i=0;i<200005;i++)
          flag[i]=0,ind[i]=0;
          
          for(int i=0;i<n;i++)
          cin>>m,flag[m]++,ind[m]=i+1;
          int x=-1;
          for(int i=1;i<=n;i++)
          {
              if(flag[i]==1) {x=ind[i]; break;}
          }

          this loop is also go through (n+1)

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

            Yes but if n is a small number then you go through positions that you don't need to use. So if you change 200005 to n+1 it should be fine. PS: If you want you can make flag and ind vectors and assign them to the size of n.

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +1 Проголосовать: не нравится

    Because you fill arrays with zeros from 0 to $$$2*10^5$$$ for each test, so it becomes $$$4*10^9$$$ in total. You can just change your “for” from 0 to n.

»
4 года назад, # |
  Проголосовать: нравится +2 Проголосовать: не нравится

My solution for $$$E$$$ to find all nodes which belongs to cycle or not:
Use bridge finding algorithm, and if an edge is not a bridge then two nodes connecting this edge will be in cycle, so mark them. code.
PS : Simple dfs would have worked, but almost always i end up in an infinite loop, when writing dfs code to find nodes that are in cycle.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can somebody help me understand how this submission got hacked? Is it some Java stuff?

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

    Change the size of your cnt array from 200001 to n+1. Because if number of test cases is 20000, total no. of operations will be 4∗10^9 which will result in TLE

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

Anyone use random shuffle to solve A?

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

    Yes you

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

    did random shuffle passed test cases

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

      Random shuffle till find a valid solution passed.

      • »
        »
        »
        »
        4 года назад, # ^ |
          Проголосовать: нравится +9 Проголосовать: не нравится

        This solution is not wrong. We only need a few random shuffles to get the correct solution.

        What the problem asks (find a permutation such that P_i != i for all i) is basically to find a derangement of the permutation.

        More about derangement can be found here.

        The probability of getting a derangement from all permutations of length N is !N / N!. The value of !N / N! approaches to 1 / e = 37%

        Let's say we want to do random shuffle X number of times such that the probability of getting a derangement is at least 99%.

        Then, (0.37)(1 — (1 — 0.37)^X) / (1 — (1 — 0.37)) >= 0.99 This gives us X >= 10, so doing 10 random shuffles already gives us 99% chance of getting a valid derangement.

        We can increase X to 50 to increase the odds. We can also just random shuffle until we find a valid solution like you did, which can be expected to use at most 50 shuffles.

        This gives us a O(50TN) solution which gives accepted.

        An example demonstration of using 50 random shuffles here

»
4 года назад, # |
Rev. 2   Проголосовать: нравится +4 Проголосовать: не нравится

problem C got weak testcases. Someone from the Egyptian Olympiad in Informatics(so I know him) passed problem C with a wrong solution so I hacked him. Surprisingly after system testing, I found that this is the only case that made him fail and if I didn't hack him, he was going to pass system testing. Oh, and also I found out that around 12 people also failed on the case(My case: Case#7). So around 12 people were going to also unfairly pass.

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +5 Проголосовать: не нравится

    what is your test case??

    • »
      »
      »
      4 года назад, # ^ |
        Проголосовать: нравится +6 Проголосовать: не нравится

      My testcase was a randomly generated array of length $$$2*10^5$$$. The elements in the array were from $$$10^5$$$ to $$$2*10^5$$$. A lot of people have done the mistake of doing a frequency array of size $$$10^5$$$ or $$$10^4$$$. Now you wonder, why they did the frequency array so small that would give runtime error or wrong answer? Here is my answer:

      1)Some people didn't notice the mistake. They were gonna pass unfairly.

      2)Other people who didn't use memset or a fast method of memory allocation in each testcase, the person got TLE with $$$2*10^5$$$. So the person decreased the allocation to $$$10^4$$$ surprisingly, it passed system testing and was going to pass all system testing.

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +5 Проголосовать: не нравится

    A stress test was missing in the pretests... An array of largest size with all elements equal was an easy hack for my solution (TLE but could be easily fixed if I TLEd a pretest). Was pretty happy that I did ABCDF then got hacked on C :/

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

can anyone pls tell me at which test case my code is failing.

link of my solution : https://codeforces.me/contest/1454/submission/99488821

»
4 года назад, # |
  Проголосовать: нравится +5 Проголосовать: не нравится

I solved F using segment trees and binary search in O(nlog² n). Submission.

Code
»
4 года назад, # |
  Проголосовать: нравится +7 Проголосовать: не нравится

How to approach E if there were more than N edges ?

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can someone explain why my submission is showing wrong answer on test case 4 even though it is right? https://codeforces.me/contest/1454/submission/99475597

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Alternative solution for F. Lets iterate through all values, and try to make each value minimum of second block. If we are trying to make $$$a_i$$$ minimum, we should find first value left to i, such that $$$a_k<a_i$$$, first value after i, such that $$$a_j<a_i$$$. Now we know, that second block lies somewhere in $$$(k, j)$$$ (otherwise, it`s minimum will be less then $$$a_i$$$). Lets just check second blocks $$$(k+2, j - 1), (k+2,j-2), (k + 1, j - 1), (k + 1, j - 2)$$$. Why check this values? Sometimes it might be, that array looks like $$$a_k, a_i, a_i, .... $$$, and we want prefix to have $$$a_i$$$ in it, same thing with suffix. We can try using segment tree. $$$O(n \log n)$$$.

https://codeforc.es/contest/1454/submission/99479843

»
4 года назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

I came up with simple approach in F.
First we will build min and max sparse table so that we can get min and max values in O(1).
Its easy to observe that as we increase length of a segment, maximum value increases , and minimum value decreases.

Using this observation : For every possible X from 1 to n-2, we will find lower bound(l) and upper bound(u) of possible value of Y. This can be done using binary search. The third segment ,if possible, will lie in between (l+1) to (u), and this can also be found using binary search.
If at any point we are able to find first, second and third segment, We will print it. Else No possible answer is there.
Using this approach, we can further extend the problem to calculate all possible X,Y,Z which satisfy the given conditions.
Time Complexity -> O(nlogn). Submission link -> https://codeforces.me/contest/1454/submission/99541373

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

    That is exactly what I've done but I used seg trees for min and max xD but it worked. And yep, I agree that the idea of that solution so simple. I got the idea in only 10 minutes(and 30 minutes implementing and debugging due to the fact that I don't have a segment tree template :c).

»
4 года назад, # |
Rev. 3   Проголосовать: нравится -6 Проголосовать: не нравится

deleted

  • »
    »
    4 года назад, # ^ |
    Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

    You should paste the link or put your long code into the spoiler

    Like this
»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

In F solution by gassa why u=min(x[lo-2],a[lo-1]) i.e why x[lo-2] is here?

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

    The maximum on the updated left segment, [0..lo - 1), is just stored in x[lo - 2].
    The middle segment just got a[lo - 1] added to it, so it can contribute to the minimum on the middle segment.

»
4 года назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

Question D is very good

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can someone explain problem D for me? I am having a hard time understanding the explanation

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

When we do cnt * (n-cnt), arent we counting some edges multiple times? Lets say we have two vertices on the cycle each with a tree of size k. Then for both vertices we do k*(n-k). So, arent the paths between both trees counted twice? Can you please correct me where I am going wrong.

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

    I also think you are correct. I think there's a typo in the editorial for E and answer should be:

    for all cnts in cycle: cnt * (cnt — 1) + (cnt * (n-cnt) / 2) where the division is not integer division.

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

      I'm an idiot, I should've thought about it more before commenting. What you're saying is true, the paths do look like they are being counted twice. You would normally expect it to be divided by 2. However, each time a node from a tree finds a path to another node that's in another tree, there are two ways to get there; it can either go clockwise around the cycle, or go anti-clockwise. This means this multiply-2 from going clockwise-anticlockwise cancels out the divide-2 from the paths being counted twice. So in the end, it's cnt*(n-cnt).

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

can anybody tell me what's wrong with my code problem C got WA, D got TLE sorry for bad quality because I coded those in a rush

UPD: i knew my problem D code was wrong because i didn't check all primes possible but why was that TLE'ed

C: 99488693 D: 99475141

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can someone explain why did this solution TLE's? My Solution

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

    It's giving TLE on test 2 which has 2e4 testcases. Now, in your code, you are running this loop: for(int i = 0 ; i < ARR+2 ; i++) lastocc[i] = -1; where ARR = 2e5+2. Hence, in total you are doing computations more than 2e4*2e5=4e9, which is causing TLE.

»
4 года назад, # |
Rev. 2   Проголосовать: нравится +8 Проголосовать: не нравится

Interesting fact: author's solution problem D have time complexity $$$O(\sqrt{t\cdot N})$$$, where $$$N$$$ is sum $$$n$$$ for all test cases ($$$N <= 10^{10}$$$).

Proof:

Spoiler
»
4 года назад, # |
Rev. 5   Проголосовать: нравится 0 Проголосовать: не нравится

can someone explain to me the problem 3? i don't get the editorial.

also, i have a different approach of the problem, i don't know why it doesn't work.

the main idea of my solution is that for each element, we split the integers according to the element and and get the minimum size of the splitted integers.

so in the last test
11
2 2 1 2 3 2 1 2 3 1 2

if i split the 3, i get
2 2 1 2
2 1 2
1 2

which is equal to 3

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

    In fact it works, with a little improve.

    let x be the value we are trying. (For each value we only do it once) We need some way (you can think about it) to help us get to the next position NXT in the array that a[NXT]==x in O(1). Instead of go though all the array and find.

    so the total time need is O(n) after the improve.

    There are some parts need to be careful, It is easy to write wrongly.

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

      then i don't know why my code doesn't work. is it because i made the array into string? here is my code:

      int n=sc.nextInt();
      String ns="";
      Set<Integer> sets= new HashSet<>();
      for(int i=0;i<n;i++){
                      int x=sc.nextInt();
                      ns+=Integer.toString(x);
                      sets.add(x);
      }
      int min=Integer.MAX_VALUE;
      for(int x:sets){
                      String[] nArr=ns.split(Integer.toString(x));
                      List<String> list = new ArrayList<>(Arrays.asList(nArr));
                      list.removeAll(Arrays.asList("", null));
                      if(list.size()<min){
                          min=list.size();
      }
      }
      System.out.println(min);
      

      the first thing i did is to make the array into string and use the split() function to split the array and convert the splitted string into arraylist so i can remove the empty strings

      • »
        »
        »
        »
        4 года назад, # ^ |
        Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

        I don't know much about java but I think the split() function take O(n) time to split the array, so the total is still O(n*n). If there is no problem with the time we can use string, it's easy to write. But I don't suggest to use string to often.

        //In c++ there are lot of string operator are not O(1), but greater than it.
        string s="";
        s+='a'; //this is O(1);
        s='a'+s; //this is O(length of s);
        //if we do s='a'+s n times, it is O(1+2+3+...+n) = O(n*n)
        

        We need to use a list or array to save where the next number is. For example.

        a[] = {1,3,2,4,4,1,2}.
        
        nxt[1][]={0,1,5,8}
        nxt[2][]={0,3,6,8}
        nxt[3][]={0,2,8}
        nxt[4][]={0,4,5,8}
        
        

        we add a '0' in the beginning and a 'n+1' at the end. Then for each number check throw nxt, to calculate the answer.

        we don't have space so save a array size[2e5][2e5]. So use a list or vector.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can someone explain to me how the proposed solution for D didn't send TLE when in the worst case scenario you'd have to check if the numbers are divisible by any of all values up to 10^5? And here I was thinking of how to optimize it to reduce it to sqrt(10^5) and only checking with prime numbers using a sieve lol.

For reference, using the method above, it takes way more than 10 seconds when testing the number 9999999769, which could perfectly fit into a test case.

This is my first time competing in codeforces, which probably explains my confusion. Anyways, any help with my doubt is appreciated :)

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

    If you can put you code I can see the problem. I'm not that good at English.

    Here is some of my understanding.

    First you only need to check the prime number from 2 to sqrt(n). Why? Because if we check from 2 to sqrt(n) and there is no prime number that n%P==0. We can confirm that n is a prime.

    So there is no need to check the rest of it.

    If the smallest prime factor of n is greater then sqrt(n) then n is a prime. Because if there is P1>sqrt(n) and P2>sqrt(n) there is no way P1*P2<=n.

    Here's how I divide a number in to prime factors

    cin>>n;
    int tmp=n;
    for(int i=2;i*i<=n;i++) 
    {
        while(tmp%i==0)
        {
            cnt[i]++;
            tmp/=i;
        }
    }
    if(tmp!=1) cnt[tmp]++;
    

    Of course tmp can be very big, it need to be write like this

    cin>>n;
    int tmp=n;
    for(int i=2;i*i<=n;i++) 
    {
        if(tmp%i==0) p[++tot]=i;
        while(tmp%i==0)
        {
            cnt[tot]++;
            tmp/=i;
        }
    }
    if(tmp!=1) p[++tot]=tmp,cnt[tot]++;
    
»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Hi all. in problem d i have made certain observation.

  1. if the number is prime we cant do much we print the number itself

  2. if the number is not prime then i observed and did this

-> count all the prime factors and the frequency. The maximum frequency will be the length.

-> what i observed is only 2 3 5 and other prime numbers are the only prime factors of a number. for example 65=5*13 8=2*2*2 and so on

now what i did in my code. first i checked whether a number is prime or not if it is then i did step 1 and if not i count all the 2s 3s 5s and other prime numbers if any

after all the counting if the max freq is 1 then printing the number itself ,if not then printing the minimum prime factor according the max frequency

now my problem is that my code is giving TLE like hell because my code for checking prime number is inefficient

so i want to know if my concept and approach is correct at all and if so how to optimize my code?

  • »
    »
    4 года назад, # ^ |
    Rev. 6   Проголосовать: нравится 0 Проголосовать: не нравится

    I sorry to say that you way is half correct.

    If the number is small, you solution can solve it.

    The way you check prime number and the way you calculate all the prime factors is a bit slow.

    here's how I get prime factors.

    cin>>n;
    for(int i=2;i*i<=n;i++) 
    {
        while(n%i==0)
        {
            cnt[i]++;
            n/=i;
        }
    }
    if(n!=1) cnt[n]++,n=1;
    

    the most improtant part is i*i<=n. you only to check O(sqrt(n)) time.

    the if after is also necessary.

    For example n=21, first you get 7 after /3. Then quit the loop. But 7 is a prime factor. So if n!=1 after the loop then n must be a prime factor and it only appeared once.

    You can try some number and have a deeper understanding.

    This solution is O(sqrt(n)). There are faster solution but you need to learn more. Like how to get prime number from (1 to n) in O(n).

    I hope this will help you.

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

RESOLVED

In problem A, I wrote

for (int i = 0; i < n; i++)
         {
            cout << (i + 2) % n << " ";  
         }

instead of

		for (int i = 0; i < n; ++i) {
			cout << (i + 1) % n + 1 << " ";
		}

as shown in the editorial, but get output : 0 1 \n 2 3 4 0 1 for the input: 2 2 5 I think the codes are implementing the same thing. I have looked through c++ reference for the error, and searched "Modulo error" to find the reason, but I don't get anything useful. Can I have any hint or any keyword to search on Google about why this is happening?

Thanks!

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +1 Проголосовать: не нравится

    They are obviously not the same thing

    $$$(5+2)\operatorname{mod}7=0$$$
    $$$(5+1)\operatorname{mod}7+1=6+1=7$$$
  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    I don't know whether this is you problem.

    In the first way, 0<=(i+2)%n<n

    In the second way, 0<=(i+1)%n<n , 1<=(i+1)%n+1<=n

    So your output has a zero. You need to place that +1 after modulo to get value from (1 to n).

    For example you want to get random number from (1 to 10). you need to write rand()%10+1 instead of rand()%10 or (rand()+1)%10. There is a difference

    Is this you problem or I misunderstand it.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

For E Is there proof that it will have always 1 cycle?

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

    use n-1 edges to build a tree first (link u[i] to v[i] if they are not connected) (or u[i] to v[i] is the 'last edge')

    then transform the un-root tree to a root tree

    the 'last edge' is from u to v

    then the cycle is (root to u),(u to v),(v to root)

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

The O(n) solution of promble F is very valuble.

Here is my solution .I improve it from the O(nlogn) solution.

let L be the left point, R be the right point. we can find that when L is increasing R decrease. also we can find that for one L there is only one R may be the answer.(there can be several but they are all the same.)

let lmax[L] be the maximum value from 1 to L, rmax[R] be the maximum value from R to n.(lmax[L]==rmax[R])

if there is k that (rmax[k]==rmax[R] && L<k && k<R && a[k]<rmax[R]) then the min value from L+1 to R-1 must smaller than rmax[R].we can skip all those R and go left.this can be checked in O(1) after some caculation outside the loop.

finally it will look like this .....a[L]......a[k]==a[k+1]==...==a[R-1]==rmax[R]....

a[k] is the last left number equals to rmax[R].

let just save the L and R and calculate it later.

here is a small problem, this is ok for lmax[L]==rmax[R] < MAX, I don't know if it also work when lmax[L]==MAX. so I take the part (lmax[L]==rmax[R]==MAX) out and solve it individually.

when calculate L[i] and R[i], we can go backward, so we can update the min value from L+1 to R-1 in O(1) , becuase we are adding number to the set.

I think the method that add a number to the set and get MAX or MIN instead of erase from the set is pretty important.

here is my code I not really good at it so is a bit long

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

but there is another approach without any graph algorithms that works very well for such kind of graphs

vovuh Is the leaf trick that you mentioned in the editorial of problem E, a particularly classic known idea / algorithm ?

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

I am applying seg tree+ 2 pointers in problem F ,but it gives WA on test case 2 (case 721) . Could anyone pls help me ? Here's my code :

99797628

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can somebody please help me with my code, its for problem E, I keep getting MLE and i just cant understand why? 100473133

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

In problem E, why does a normal BFS/DFS lead to MLE on test 2?

The memory limit seems to be sufficient.
I even tried declaring global arrays and with a maximum size of 100 to at least pass test 2, it still resulted in MLE. vovuh can you explain please?

PS: Solved it finally but had to rewrite from scratch (without using any boiler plate code). Not getting what's the problem with the previous one. Will using one/two extra vectors of $$$O(n)$$$ size make any difference?

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

I have solved F with segment trees and the two-pointer algorithm. So I have a start(== 0) and end(== N-1) variable. I have segment trees to query maximum from ([0, start], [end, N-1]) and minimum from ([start+1, end-1]). Now my segments are [0, start], [start+1, end-1] and [end, N-1]. My aim is to increase max1([0, start]) and max2([end, N]) as gradually as possible. Now in our while loop if max1 == max2 == min(from [start+1, end-1]) then we have found a solution otherwise we have to update start and end.

So if(max1 < max2) or (max1 > max2) I will start++ or end-- accordingly. But if max1 == max2 then I will compare A[start+1] and A[end-1] and if they too turn out to be equal then I will compare A[start+2] and A[end-2]. So even if I have a case where start+1 and end-1 point to equal elements I will make sure that the increase in [0, start] and [end, N-1] is gradual. 142372335 ~~~~~ Your code here... ~~~~~

ll N;
    cin >> N;
    vector<ll> A(N);
    for (ll i = 0; i < N; i++)
        cin >> A[i];
    vector<ll> segmentMin(4 * N, LONG_LONG_MAX), segmentMax(4 * N, LONG_LONG_MIN);
    buildMin(0, 0, N - 1, A, segmentMin);
    buildMax(0, 0, N - 1, A, segmentMax);
    bool possible = false;
    ll start = 0, end = N - 1;
    while (start + 1 < end)
    {
        ll max1 = queryMax(0, 0, N - 1, 0, start, segmentMax);
        ll max2 = queryMax(0, 0, N - 1, end, N - 1, segmentMax);
        ll min1 = queryMin(0, 0, N - 1, start + 1, end - 1, segmentMin);
        if (max1 == max2 && max1 == min1)
        {
            possible = true;
            break;
        }
        if (max1 < max2)
            start++;
        else if (max1 > max2)
            end--;
        // max1 == max2
        else
        {
            // we want to slowly increase max1 and max2
            if (A[start + 1] < A[end - 1])
                start++;
            else if (A[start + 1] > A[end - 1])
                end--;
            // ultimate slow increaser
            else if (start + 2 <= end - 2 && A[start + 2] < A[end - 2])
                start++;
            else
                end--;
        }
    }
    if (possible == false)
    {
        cout << "NO\n";
        continue;
    }
    cout << "YES\n";
    cout << start + 1 << " " << end - start - 1 << " " << N - end << "\n";
»
8 месяцев назад, # |
Rev. 5   Проголосовать: нравится 0 Проголосовать: не нравится

problem c

10

1 5 2 5 6 5 10 10 7 1 2

how is this going to be 1 !?????????????????????

I wasted 2 hour and it seems that I can't even get what the problem want