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

Автор NBAH, история, 8 лет назад, По-русски

A

Научимся определять расстояние между точками. Далее, зная, что время — это расстояние делить на скорость, будем определять время для каждого таксиста, за которое он сможет доехать до Василия. Ответ это минимальное из времен.Не забудем про double.

Асимптотика O(n).

Решение

B

Пусть c[x] — количество магазинов в которых цена за напиток равна x. Посчитаем для этого массива префиксные суммы. Далее возможные следующие варианты:

1)Если текущее количество денег у Василия больше, чем размер массива с префиксными суммами то выводим n.

2)Иначе выводим префиксную сумму для количества денег, которое сейчас у Василия.

Асимптотика O(q+n).

Решение

C

Будем решать задачу динамическим программированием. dp[i][j] это минимальное количество энергии, которое надо потратить чтобы расположить первые i строк в алфавитном порядке и i-ая из них будет перевернута если j=1 и не перевернута если j=0. dp[i][j] обновляем через dp[i - 1][0] и dp[i - 1][1]. Остается проверить, что i-ая строка лексикографически больше (i - 1)-ой(если j=1 то проверяем перевернутую i-ую строку, аналогично для (i - 1)-ой). После чего обновляем dp[i][j]=min(dp[i][j],dp[i - 1][0]+c[i]*j), dp[i][j]=min(dp[i][j],dp[i - 1][1]+j*c[i]). Ответ это минимум из dp[n][0] и dp[n][1].

Асимптотика O(n+sum_length).

Решение

D

Каждое число из множества будем хранить в двоичной системе счисления(каждое число будет состоять из 32-х 0 или 1) в такой структуре данных как бор(рёбра — это будут биты 1 или 0, а вершины будут отвечать за то, можно ли пройти по текущему ребру). Чтобы ответить на запрос типа "? x" будем спускаться по бору от старших битов к младшим и смотреть можем ли мы сейчас ксором в i-м бите получить единицу, если можем, то переходим, иначе идём туда, куда можем идти.

Асимптотика O(q*log(10^9)).

Решение

E

Обнесем матрицу рамкой из фиктивных элементов. В каждом элементе матрицы и рамки храним значение элемента номер элемента соседнего справа и номер элемента соседнего снизу. Когда приходит запрос поменять местами прямоугольники надо поменять значения элементов только по периметру прямоугольников.

Асимптотика O(q*(n+m)).

Решение

Разбор задач Codeforces Round 367 (Div. 2)
  • Проголосовать: нравится
  • +37
  • Проголосовать: не нравится

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

Problem B can be easy solved using Binary search

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

Как можно решить задачу D не используя Бор? Слышал что можно решить деревом отрезков.

Заранее спасибо :D

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

    Я так думаю имелось ввиду дерево отрезков, которое в точности отображает работу бора в этой задаче, точнее им же и есть, просто интерпретируй вершину не как i-бит а отрезок размера 2i. Код абсолютно такой же, просто название другое.

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

      Можно про решение деревом отрезков поподробнее?

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

        Построим дерево отрезков на промежутке [0;230 - 1], только храним дерево не массивом а указателями, так как некоторых вершин не будет в принципе. Теперь можем заметить, что когда мы находимся на высоте h + 1. (Высота корня — 30) то если мы идем в левого сына, то все числа на этом отрезке будут с ноликом на бите h, если вправо то с единичкой в бите h. Ну к примеру с корня можем пойти в [0;229 - 1] и [229;230 - 1] , все числа на первом отрезке имеют нолик на 29 позиции, а на втором отрезке — единичку. Таким образом, если мы идем влево — ноль, вправо — единичка. Дополнительно стоит хранить количество чисел на отрезке, и тогда если пришел запрос добавить число или убрать число то мы как в обычном дереве отрезков прибавляем 1 или отнимаем 1 от соответствующего элемента, а когда запрос максимума то жадно спускаемся и пытаемся на высоте h идти в бит противоположный чем в числе y, если не можем пойти (кол-во чисел == 0), то идем в такой же бит. Но тот же самый бор, просто обозвали иначе.

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

    сам сдал бором, но еще вижу решение отсортированным сетом (пока предположим, что каждое число встречается не более раза, переход от сета к мультисету зависит уже от языка). В сете хранятся текущие числа, при выполнении запроса, нужно сделать аналог спуска по бору, и проверять не наличие вершины с соответствующим бита, а наличие чисел в сете в определенном отрезке, начиная с [0, 2^31-1] и по мере спуска модифицировать его

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

    хранишь в мультисете значения, по + просто запихиваешь их туда, по — просто вынимаешь один, а по запросу — инвертируешь число х и пытаешься по сету аппербаундами найти число, наиболее похожее на это O(qlog(10^9)log(n))

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

      "пытаешься по сету аппербаундами найти" — можете объяснить, что это значит?

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

        сет — структура данных set st

        аппербаунды — st.upper_bound(value), лень было писать на английском тогда

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

Слишком короткий(унизительный) разбор.

После прочтения кажется, что ты тупой.

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

    Я после каждого разбора чуствую себя тупым :D

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

этот момент, когда разбор задачи Е длиннее только разбора задачи А

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

Don't understand the approach for E ! Can someone explain it better ?

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

    This problem is an exercise in Linked Lists: store the matrix as a 2D array of elements each of which has links to its upper, lower, left and right neighbours. To swap two rectangles you only need to consider their borders. Tear the rectangles off from the matrix by erasing the needed links (i.e. erase all upper neighbour links to tear the upper border of a rectangle) and stitch them back in each other's spots. Note that you lose the ability to ask for a cell in (r, c) by a 2D array lookup but should instead start from the upper left corner and walk r down and c right links.

    To avoid null pointers, surround the matrix by a frame of fake cells, as the editorial suggests.

    Example solution: http://codeforces.com/contest/706/submission/19808792

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

    One thing to note about swapping submatrices is that the actual submatrix "structure" doesnt change, take a look at the following masterpiece (orange is left neighbour, red is right, blue is up, and green is down).

    so say i swap the top left 2x2 submatrix(1,2,5,6) with bottom right 2x2 submatrix(11,12,15,16). the INTERNAL arrows never change, because the actual submatrices still have the same elements. However, the perimeter arrows change, because we now have new neighbours due to swapping matrices. In order to fix the structure, all we have to do is swap the corresponding perimeter arrows, so for example 15 green arrow will point at 9, 12 red arrow will point at 3 etc.

    hope that helps!

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

    Help with solving E needed, I got TLE on test 10 all the time, could anyone explane why does it give TLE? Check the last submission pls http://codeforces.com/submissions/GuralTOO

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

      Got rid of TLE, by simply using scanf/printf now have trouble with WA..

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

        Check your nested for loops, some of them are for looping n then n, rather than n then m (which explains why you get WA on that testcase, because its the first one where n<m, so some ids arent assigned).

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

          Man, thank you a lot, was typing fast, so didn't notice.. that fault, thank you again

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

why this submission: 19811194 gets memory limit exceeded?? It's memory complexity is O(q lg MAXa) which is ok for this problem!

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

    i am not sure but maybe this is the reason :

    you are right about O(q*logMax) but here you have a constant like 2*5=10. 2 because of creating both nodes at each step not just one. 5 because of struct size (pointer size is 32 bit).

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

Thanks for a really awesome problem set. Really enjoyed the contest.

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

Isn't complexity of D just O(q)? That log factor is constant.

Btw, u can solve D without any data stucture, finding bits from most significant one with lowerbound on set. The main idea is the same, but u don't have to know trie. Here's my code — 19807490, complexity is O(q*log(q)).

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

    please be more specific on your binary search on set please?

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

      Ok, look. First of all we have l = 0, r = maximal value of unsigned int. y = bitwise negation of x — best-case scenario for xor, our reference point. We look over bits of y from 31th to 0th.

      If pth bit is set (y & (1<<p)), we'd like to set that bit in our answer. We can use lowerbound to find out if set contains at least one number in range [l+(1<<p), r]. It can't be less than l+1(<<p) or greater than r, because we have to satisfy assumptions about more significant bits we've made before (l, r), and also we want pth bit to be set (1<<p). If we satisfy that condiotion, then [l, r] becomes [l+(1<<p), r], otherwise it becomes [l, r-(1<<p)].

      If pth bit of y is not set, we don't want to set it in our answer. We use lowerbound to check if set contains some elements in range [l, r-(1<<p)]. If it does, we set r to r-(1<<p), otherwise l becomes l+(1<<p).

      After loop we have l = r, and we output this number xor x.

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

У меня почему то в C WA 12 хотя все как в разборе

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

    Руки кривые.

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

      Лучше бы причину ошибки человеку написал.

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

    Ну в у вас в пересчете динамики полный отстой написан. Посмотрите на мой код. А еще у вас функция r за квадрат работает

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

In the explanation of problem D, what does RRF mean?

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

i have problem with time complexity analysis of problem C. let us do worst time complexity analysis. for each case say we have to reverse . reverse function has linear time complexity and for each case we are reversing hence time complexity should be O(n^2) or 10^5 * 10^5 = 10^10.i think then this algorithm should get time limit exceeded verdict in test case where reverse permutation of a string of length close to 10^5 is used.

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

    From the problem statement: The total length of these strings doesn't exceed 100 000.

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

      Yeah: the reverses and comparisons will alltogether be O(n), or amortized O(1).

      Also imagine that your worst case was possible, it would mean that each string has 10^5 characters, which means you couldn't even input the input without getting TLE.

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

I have a solution for problem C that does not need DP 19812078:

It basically "tries" both the string and its reverse against all possible previous choices.

class Choice(String s, Long cost)

choices := List.of(new Choice("", 0))

for (cost <- costs) {
  s := readInput()
  r := s.reverse()
  current := List.of(new Choice(s, 0), new Choice(r, cost))
  next := new Map<String, Long>() withDefault Long.MAX

  for(c1 <- choices) {
    for(c2 <- current) {
      if (c1.s.isEmpty || c1.s <= c2.s) {
        next[c2.s] = min(next[c2.s], c1.cost + c2.cost)
      }
    }
  }
  choices = next.map((k, v) => new Choice(k, v))
}

if (choices.isEmpty) print(-1) else print(choices.values.min)
  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится +1 Проголосовать: не нравится

    So you only store the last row in your DP

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

      Exactly: it's still the same logic as the regular DP.

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

        Ah, you are right — now I see the similarity. Atleast when I was writing the code, I did not think I was doing DP :)

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

          Brute force would be if you also went all the way back to the first string when trying an option for the current one. Using the fact that the previous string is enough (and storing the corresponding scores) makes it DP :))

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

Hi, last night I misunderstood the problem C:

  • they said "total length of the strings <= 100 000"

  • but I thought "length of each string <= 100 000"

So I came up with the idea "how to compare 2 strings only in O(log(length(string)), and we also don't have to reverse it in O(length)", based on binary search. Thus, the general complexity is O(qlog(length))

So I wrote a "compare(string s1, string s2, int type)" function:

  • type = 1: compare non-reverse s1 and non-reverse s2

  • type = 2: compare non-reverse s1 and reverse s2

  • type = 3: compare reverse s1 and non-reverse s2

  • type = 4: compare reverse s1 and reverse s2

Then I submitted and got WA, so I hope somebody could take a look at my submission and point out what I was wrong. I'm sure I got wrong in my "compare" function because when I use standard "compare" and "reverse" functions of C++, I got AC ( of course the complexity now is O(length) ).

Ty in advance.

My submission: 19808155

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

    Binary searching like this is wrong, because comparing the middle of two strings doesn't tell you anything about the characters before it or after it. You should compare entire prefixes of the strings, and to do so efficiently you'd need hashing, but that means that before the binary search you'd already do O(length) operations for the hashing.

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

How do we prove the solution to B is correct ?

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

I still dont understand prob C. Is the dp actually like brute force? wont it take O(2^n)?

also, in prob D I tried something like putting in integer form in list. I dont understand what the editorial says when it says to put in binary.

(I am new to codeforce!!)

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

    dp isn't brute force. You update dp[i][0] and dp[i][1] in O(s[i].length). So total complexity is O(sumLength).

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

    The point of dp is to memorize previous choices that won't be affected by later choices, so that we could save the time for computing the previous choices again when we proceed to later choices.

    In problem C the states store the value of previous computed strings, since it is guaranteed that it all the previous strings have been ordered in lexicographical order (or just set the value to INF if it is impossible to do so), you only have to compare the latest string to the reversed or the original string to check the minimum costs of following the lexicographical order.

    For problem D I can't find your submission so I don't know what exactly got you, but I suppose that you have completely no idea of what the editorial is doing.

    The solution is to build a tree/trie, that stores integers in binary form (eg: 5=101(2), 7=111(2) ). You have to maintain the amount of values in the subtree in order to answer the value.

    If you don't know about Trie, or even some other tree structures like BIT(fenwick tree), read them before solving this problem, or else you will have absolutely no idea what I am explaining.

    After building the trie of the multiset, you have to check 1. if there is an edge to the left child(0) and the right child(1), and if the left/right child is empty (cnt==0). Make the optimal steps upon visiting each nodes, and sum up the values of xor for the query results.

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

I'm still learning DP, so confused about problem C.

We both know if we want apply DP to some problem, the problem must meet several conditions.One is that it must have optimal sub-structure. One is that the sub-problem has non-aftereffect property.

So here is my question, if we already solve the first i query, but the i+1 th string is smaller than the i th but the cost c[i+1] is too big, then we should not reverse the i+1 th but modify the first i string, how's that meet the optimal sub-structrue and non-aftereffect property? Because the i+1 th string has a big influence on the answer we've already calculated before.

I don't know where I get wrong, thanks for your help.(sorry for poor English

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

I have solve C using dp , but getting wrong answer. Can someone help me to debug.... I use dp1[] for reverse string and dp[] for simple string. ~~~~~ ..

#define For(i,st,ed) for(i=st;i<=ed;i++)

const ll mod=1000000007;

//Main

int main() { ios_base::sync_with_stdio(false);cin.tie(0); int test=1,i,j,n,tt;

//cin>>test;

For(tt,1,test){
    cin>>n;
    string st[n+1];
    ll dp[n+1],dp1[n+1],a[n+1];
    string s,s1;
    ScanA(a,n);
    dp[1]=0;
    dp1[1]=a[1];
    For(i,1,n)
       cin>>st[i];
    For(i,2,n){
       s.assign(st[i]);
       s1.assign(st[i-1]);
       reverse(s1.begin(),s1.end());
       dp[i]=dp1[i]=-1;
       ll x=-1;
       if(s.compare(st[i-1])>=0 && dp[i-1]!=-1)
         x=dp[i-1];
       if(s.compare(s1)>=0 && dp1[i-1]!=-1)
         if(x!=-1)
          x=min(x,dp1[i-1]);
         else
          x=dp1[i-1];
       dp[i]=x;
       x=-1;
       reverse(s.begin(),s.end());
       if(s.compare(st[i-1])>=0 && dp[i-1]!=-1)
         x=dp[i-1]+a[i];
       if(s.compare(s1)>=0 && dp1[i-1]!=-1)
         if(x!=-1)
          x=min(x,dp1[i-1]+a[i]);
         else
          x=dp1[i-1]+a[i];
       dp1[i]=x;
    }
    ll x=mod;
    if(dp[n]!=-1)
       x=dp[n];
    if(dp1[n]!=-1)
       x=min(x,dp1[n]);
    if(x==mod)
       x=-1;
    cout<<x<<endl;
}
//end of test

return 0;

}

~~~~~

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

    Side note: My personal way to set the INF for long long is (1LL<<60), I have also seen some pretty good ways such as "1234567890123456789012345LL"

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

      Or just use scientific notation, eg: 1e9 + 7 or 1e18. I think it's more understandable and not as much error-prone as "1234567890123456789012345LL"

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

        1e9+7 and 1e18 are without doubt great ways to do it too, it's just a personal preference after all. =D

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

Explain prob D more properly plz . Whats RRF?

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

По моему разбор Е неполный и не отражает в действительности решения автора задачи. Можно попросить ссылку на код?

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

    Я сейчас долго писал примерно то, что написано в разборе и оно никак не работало. В итоге додумав решение из разбора получилось вот что: для периметра прямоугольников меняю местами ссылки на соседние элементы справа и снизу. Только для левого ребра я меняю местами значения элементов (потому что я восстанавливаю ответ через соседей справа, если бы восстанавливал ответ через соседей снизу, то нужно было бы менять значения для верхнего ребра). Вместо того, чтобы менять местами значения, можно было бы их вообще не трогать, но тогда нужно было бы найти соседние элементы слева от левого ребра и у них поменять местами ссылки на соседей справа. Но (!) самое важное, о чем не написано в разборе, надо "дойти" до прямоугольников. Нельзя просто так начинать что-то менять. Нужно от дополнительной рамки двигаясь вправо и вниз по соседям добраться до прямоугольников. Лично я до этого не сразу догадался, а спустя почти 2 часа.

    Вывод: разбор можно было написать и по подробнее.

    UPD: Описанное выше решение у меня так и не удалось довести до ума, а именно — избавиться от ошибки исполнения. Вместо этого я упростил это решение. Двигаясь от рамки я дохожу не до самих прямоугольников, а до рамки вокруг них. И соответственно для верхних рёбер рамок я меняю местами ссылки на элементы снизу, для левых рёбер рамок я меняю местами ссылки на элементы справа. То есть я обеспечиваю "вход" в прямоугольник. Для обеспечения "выхода" нужно произвести замены для нижнего и правого рёбер прямоугольников. Значения элементов матрицы при этом вообще не подвергаются изменениям.

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

Can anyone please explain the D solution in more detail or from another perspective?

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

What does the announcement mean ? "The lexicographical order is not required to be strict, i.e. two equal strings nearby ARE ALLOWED."

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

    That means it's still ok if s1<=s2 , it's not required for s2 to be strictly than s1 (i.e. s2>s1) to be considered as being ordered lexicographic-ally.

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

Автор решений к задачам, а вам известно о наличии встроенных функций hypot, reverse и операторов <= , < и тд для строк?

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

Link for Solution of problem C gives error

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

Solution for D with std::multiset: just like in solution with trie, for the ith bit, first we try to get 1, if it's not possible we will get 0. But we can check this using lower_bound.

Code: 19826426

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

The solution for problem E is just beautiful :)

»
8 лет назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится
These are the first few lines of Test #7
100
? 1
+ 1
+ 4
? 5
...
My code prints
1
4
But judge prints
1
5

Please explain how output is 5 for second line.
I got 4 by computing: max(5 XOR 1, 5 XOR 4) = max(4, 1) = 4
Thanks in anticipation.
»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Just use upper_bound for 2nd question

cout << (upper_bound(v.begin(),v.end(),m)-v.begin())<<endl;

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

If anyone is interested in practicing problems similar to problem D, here is a question I realized that the solution is quite similar to problem D.

282E — Sausage maximization

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

I just want to make something sure about problem E. a)Swapping two rectangles like the red and green one is not allowed, right?

b)And if such an operation were allowed, would there be an efficient method to solve this problem?

update: solved it. So, I am clear about (a). So if anyone could tell me about (b)...

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

    I have never implemented this but I think this may work.

    1) Keep two vectors of coordinates of the perimeter, ordered corresponding to their position.

    2) When swapping, check if the block next to the swap is occupied by another block. If no, just do the operation required for E. If yes, check for the corresponding position in the original block, and link it to it.

    Keeping the difference in position of the blocks should help speed up the look-up process to O(1), so the whole algorithm should work in O(n).

    This is not applicable for overlapped blocks though.

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

Does anyone have an idea for problem E in O(qnlogn) ? With data structures like segment tree?

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

    yeah that what i thinked of i think it's possible to do it with 2d segment tree with lazy propagation and it will be q*log^2(n)

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

For the 1-dimensional version of Problem E, is there a solution with faster than linear time swaps?

So in the 1-dimensional version, instead of swapping rectangles in a matrix we're swapping ranges in an array: each task is (a, c, w) and we want to swap the values in [a, a + w) with the values in [c, c + w).

And with n items and q swap queries, we want an O(q * logn + n) algorithm, or just anything faster than O(qn).

With the linked list solution in the post (which is super cool to me!), in the 1-d case it takes O(n) to find the rectangles, even though it's an O(1) swap after finding

I was trying to do something with a binary search tree: each range corresponds to <= logn nodes in the tree, so maybe you could swap ranges by swapping only those logn nodes somehow, and their sub-trees would automatically come with them.

The problem is that the ranges don't "line up": I somehow managed to convinced myself this wasn't really a problem, but I was totally off, and it is a serious issue, as far as I can tell.

Anyway, yeah, is there a quicker solution to the range-swapping problem? I.e. like an O(n) size data structure on n items which supports fast range swaps?

EDIT: answer to question = yes treap

weaker guarantees than with treap i'd guess, but i think a skip-list would work too with high probability. You can find ranges quickly and then edit O(# lists) = O(log N) pointers.

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

    Treap makes swaps in O(logN)

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

      EDIT: I'm not sure if what I said below really even makes sense actually; I'll think about this for a bit/try to understand treaps better.

      EDIT2: Okay I sort of get how the treap might work, although I'm still not sure how it'll necessarily stay balanced after lots of swaps (with high probability I guess? or it happens only after many swaps, so you can amortize any rebalances if they're needed or something).


      Thanks a lot for the response! I didn't know about treaps, they're really cool!

      But I don't see how a treap would do it though. This is how I imagine a treap approach would go:

      You construct a treap on [0, n), say as a balanced BST (and then assign the corresponding priorities).

      And then on a query (a, b, w) with a < b, you split the treap into 5 smaller treaps, t1=[0, a), t2=[a, a+w), t3=[a+w, b), t4=[b, b+w) and t5=[b+w, n)

      Then we merge them back together in the order t1, t4, t3, t2, t5.

      Splits and merges are fast, so this should be fast..

      But: naively, in order for the treaps to be merged correctly, you'd need to update the priorities of every node in t4 & t2, which would take linear time.

      Maybe there's a way to store these updates to the priorities in a more succinct/clever way, but I don't see it. (of course I might be missing something!)

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

Why this solution of problem D got RE? Help me, please.

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

edit : found my mistake

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

hey guys I'm getting WA on test 91 in problem D and i have no idea why. can anyone help me? this is my submission http://codeforces.com/contest/706/submission/20033141 i would really appreciate it

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

Hello everyone!

Can you help me why I get TLE for Problem D? Here is my submission : http://www.codeforces.com/contest/706/submission/20083814 I used binary search between lo and hi, which are iterators that contains maximum values. But it got TLE on test#2. I think it's because of case when lo > hi, but I can't find out when.

Thanks in advance

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

Please fix problem D solution!!

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

I wrote about Problem C in this post here. It's an enjoyable DP question.

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

Hello Everyone, For the Problem C, I was getting Wrong Answer on test case 18 when I was setting dp[i][0] and dp[i-1][1] to LONG_MAX but when I set it to (1LL<<62) then I was getting Accepted verdict. But (1LL<<62) is less than LONG_MAX. Can anyone explain me the reason for it. Thank You in Advance. WA with LONG_MAX https://codeforces.com/contest/706/submission/48478924 AC with (1LL<<62) https://codeforces.com/contest/706/submission/48479243

Update: I found out that on my system LONG_MAX is 2^63-1 and is equal to LONG_LONG_MAX but on online judge it is different and LONG_MAX is 2^32-1

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

Why am I getting this message when I click on the solution link in problem E.

404 Not Found

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

For question D:https://codeforces.com/contest/706/problem/D

Can someone explain logic behind this submission https://codeforces.com/contest/706/submission/19826426 ? It seems extremely simplistic and doesn't seem to use tries.

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

https://codeforces.com/contest/706/submission/84959926 Please help,I am trying to do with tree,and not able to understand why MLE is coming on last test case

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

Some Please help me why I am getting WA Thanks in advance submission Link https://codeforces.com/contest/706/submission/110031654

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

Please help Me I am getting WA on Problem C TC-8 link :https://codeforces.com/contest/706/submission/110875540 Update: Got AC by using a user defined string comparator insted of integer compairing operator

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

Solution links have broken down, kindly do the needful.

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

how could i solve problem B?