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

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

552A - Ваня и таблица

В этой задаче проходило множество решений:

1) С каждым новым прямоугольником добавляется его площадь к результату, так что будем считать площадь каждого прямоугольника и прибавлять к ответу, т.е. для каждой строки x1, y1, x2, y2 прибавляем к ответу (x2 - x1 + 1) * (y2 - y1 + 1)

Асимптотика данного решения по времени O(n).

2) Просто сделаем все, что описано в условии, создадим массив и с каждым запросом будем прибавлять прямоугольник к массиву, после чего просто сложим все элементы массива.

Асимптотика по времени O(n * x * y)

C++ code Wild_Hamster

Java code Wild_Hamster

Python code Zlobober

552B - Ваня и книги

Можно вывести формулу результата:

для n < 10 ответом будет n = n - 1 + 1 = 1 * (n + 1) - 1;

для n < 100 ответом будет 2 * (n - 9) + 9 = 2 * n - 9 = 2 * n - 10 - 1 + 2 = 2 * (n + 1) - 11;

для n < 1000 ответом будет 3 * (n - 99) + 2 * (99 - 9) + 9 = 3 * n - 99 - 9 = 3 * n - 100 - 10 - 1 + 3 = 3 * (n + 1) - 111;

для n < 10sz ответом будет ;

Асимптотика по времени O(sz), где sz — длина числа.

Так же можно было просто перебрать всех возможных 10 вариантов n < 10, n < 100, ..., n < 109, n = 109 и подсчитывать для каждого результат.

C++ code Wild_Hamster

Java code Wild_Hamster

Python code Zlobober

UPD: Don't use function pow() to find powers of 10, because it doesn't work right sometimes.

552C - Ваня и весы

Переведем число m в w-ичную систему счисления. Если все разряды числа – 0 или 1, то нашу вещь можно взвесить, поставив гири, номера разрядов которых равны 1, на одну чашу весов, а нашу вещь на другую.

Если же это условие не выполняется, то пройдемся от младшего разряда к старшему и если он не равен 0 или 1, пытаемся отнять от него w и прибавить к старшему разряду единицу. Если этот разряд становится равен  - 1, то ставим гирю под данным номером на одну чашу с нашей вещью, если 0 — то не ставим гирю никуда, если иначе – то вещь нельзя взвесить по заданным условиям и ответ .

Асимптотика по времени O(logm).

C++ code Wild_Hamster

Java code Wild_Hamster

Java code Zlobober

552D - Ваня и треугольники

Переберем все возможные пары точек, проведем через каждую из пар прямую и запишем, что этой прямой принадлежат эти 2 точки с помощью map. Если на прямой находится x точек, то на самом деле мы посчитаем нашим перебором, что на ней 2 * x * (x - 1) точек. Таким образом можно завести массив типа b[2 * x * (x - 1)] = x, чтобы определять, сколько точек находится на прямой. Тогда если на прямой находится x точек, то мы теряем x * (x - 1) * (x - 2) / 6 возможных треугольников с возможных n * (n - 1) * (n - 2) / 6 треугольников. Таким образом, для каждой прямой, на которой находится x точек, мы будем отнимать от n * (n - 1) * (n - 2) / 6 значение x * (x - 1) * (x - 2) / 6, таким образом подсчитывая ответ.

Асимптотика решения O(n2 * logn).

Поскольку map очень медленный, можно было для каждой пары точек каждую прямую заносить в массив, после этого отсортировать его и искать количество точек на каждой прямой нахождением количества подряд идущих одинаковых значений одной и той самой прямой.

UPD: I am sorry, that O(n3 / 6) solutions passed, my solution with O(n3 / 6) didn't pass before the contest, so I decided, that TL 4 sec is good(it was for Java TL).

C++11 code Wild_Hamster

Java code Wild_Hamster

Java code Zlobober

552E - Ваня и скобки

Можно увидеть, что максимальный ответ будет тогда, когда скобки будут находится между двумя знаками  * , или между знаком  *  и концом выражения. Для удобства прибавим в начало выражения 1 * , а в конец выражения  * 1.

Далее переберем все возможные пары знаков  *  и попробуем посчитать выражение, поставив скобки между двумя знаками  *  для каждой пары.

Чтобы подсчитать выражение, используем две переменные x и y, в начале x = 0, y = firstnumber, где firstnumber — первая цифра выражения, тогда если следующий знак  + , тогда x = y, y = nextnumber, а если  * , тогда x = x, y = y * nextnumber. Результатом выражения будет x + y, для подсчета выражений в скобках и вне скобок можно написать функцию.

Асимптотика по времени O(|s| * 172).

C++ code Wild_Hamster

Java code Wild_Hamster

Java code Zlobober

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

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

C was awesome!

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

I made a different algorithm for B and i like share it with you:

   let ans = 0
   let sz = numberOfDigits(n)
   let ans = sz * n
   for(p=10;p<=n;p*=10)
      ans -= p-1
   print (ans)
»
9 лет назад, # |
  Проголосовать: нравится +16 Проголосовать: не нравится

It's sad to know that O(N^3) passed for problem D for some of my friends while I have been struggling to make an O(N^2 logN) algo. Why 4 sec time limit?? :(

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

in D, how did O(n^3) pass for n=2000 I got 2 unsuccessful attempt trying to hack O(n^3) solutions

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

    Codeforces servers run >10^9 operations in 1 second, they are really fast

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

      In case the server run 10^9 in 1 second, there will be no TLE for many problems. So I think maybe the large data is just too lucky --!.

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

Please check the following two codes for Problem D:

http://codeforces.com/contest/552/submission/11648893

http://codeforces.com/contest/552/submission/11646357

I think both have same time complexity (O(n^3)) but first one got accepted and the other (my solution) got TLE. Why do I get TLE error. Please let me know if I have missed something. Thanks!

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

    As you can see, you have done a lil more constant time computation and also used std::cin and std::cout for I/O while the other person uses much faster scanf and printf.

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

    the main reason of TL is long long.

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

      Woah! I never knew that the data types could affect the running time too. I made the changes and the solution got accepted. Is there an explanation to this? Thanks! :)

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

        The size of different datatypes is different. Generally the trend is, more the number of bits in a datatype, more is the time taken to perform operations on it.

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

    Input/Output — scanf/printf is much faster than cin/cout.

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

My solution for C was brute force:
if(w = 2 or w = 3)
The answer is always yes
else
Every weights has three cases:
1:on the left pan
2:on the right pan
3:unused
and the order is O(3 ^ x) where w ^ x = m

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

    Mine was exactly same as your solution but i got time limit exeeded. problem in my code was when w = 3. can you explain why the answer is always YES when w = 3? and here is my submission : 11649907

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

      3 base log of 10^9 is ~18.86 ,so the solution becomes 3^18 which gets TLE . but 4 base log of 10^9 is ~14.9 . 3^14.9 is less than 10^8 , so gets ac

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

      you can easily prove it by induction!

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

    Thanks, finally a straightforward advice!

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

My solution for C was brute force:
if(w == 2 or w == 3)
The answer is always yes
else
Every weights has three cases:
1:on the left pan
2:on the right pan
3:unused
and the order is O(3 ^ x) where w ^ x == m

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

i tried solving D in contest but got WA.here's my submission...can someone please find a bug in my solution!!

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

I don't understand the solution for problem C. Specifically the second part -

"if it becomes equal to 0, then we don't put weight, in another case we can't measure the weight of our item and answer is No."

How will it become zero? In base w, no digit will ever exceed w-1, so by subtracting w you can't get zero :/

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

    It can be w if we add one because the previous digit was greater than one.

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

      Oh ok that makes sense! Btw is there any formal proof to this thay why solution does not exist in other cases?

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

Я решал C так:

Пусть s = (1 + w1 + w2 + w3 + ... + wn), где s > m.

Тогда проверим все ли цифры числа (s + m) в системе счисления с основанием w меньше либо равны 2.

код: 11645367

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

    По-моему, самое красивое решение.

    Покапитанствую, почему оно работает (так как до самого не сразу дошло :) ): по сути, надо ответить на вопрос, существуют ли такие a и b, удовлетворяющие a + m = b, и представимые в системе счисления с основанием w в виде комбинаций 1 и 0 (притом, 1 у них не могут стоять на одинаковых позициях). Добавим к обеим частям равенства b, получим (a + b) + m = 2b. Добавив ещё некоторое c, чтобы закрыть оставшиеся 0 в сумме (a + b) единицами, получим как раз (a + b + c) + m = s + m = 2b + c, что и означает, что число (s + m) в с.с. с основанием w есть комбинация 0, 1 и 2.

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

In problem D there was also O(n^2 * maxX) solution. For each pair of points we calculate equation of line y(x). Then for each x coordinate we find y(x) and if it is integer and point (x; y(x)) exists, we decrease number of triangles by 1.

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

D passed in 1.7 seconds and it was O(N^3) 11653540

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

My solution for Problem C is very simple and it passed: http://codeforces.com/contest/552/submission/11646617

Basically, let's try to solve:

c0 + c1*w^1 + c2*w^2 + ... = m      ------ (Equation 1)

Where each c0, c1, c2 are either -1, 0 or 1.

-1 means we used the weight on right, +1 means we used the weight on left and 0 means we did not use the weight at all.

=> c1*w^1 + c2*w^2 + ... = m - c0
=> w(c1 + c2*w^1 + c3*w^2 + ... ) = m - c0
=> c1 + c2*w^1 + c3*w^2 + ...  = (m - c0)/w        ------ (Equation 2)

Now, notice equation 1 and equation 2 -- we are trying to solve the same problem all over again! So let's recurse!

For such a solution to exist (m — c0) must be a multiple of w.

Let's divide both sides by w and recursively solve if we can find such an m-c0 where c0 = -1 or 0 or 1

Here is solution in plain code:

boolean solve(int w, int m) {
  return w <= 3 || m == 1 || trySolve(w, m-1) || trySolve(w, m) || trySolve(w, m+1)
}

boolean trySolve(int w, int m) {
  return m%w == 0 && solve(w, m/w)
} 

This is also one way of proving that if w = 2 or 3 it always possible since it is guaranteed to find atleast one multiple of 2 and 3 in m-1,m and m+1.

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

    Wow, I loved this solution! Also, you have explained it very well!

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

    Really very nice idea and very nice explanation.

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

    answer for 3 105 should be YES or NO?

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

    Wow. Thank you!

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

    in trysolve function,can you explain how recursive relation is working?
    Now the remaining c1 + c2*w^1 + c3*w^2 + ... should be equal to (m-c0)/w ,
    but you are doing solve(w, (m-c0)/w) isn't this equivalent to c0*w^1 + c1*w^2 + c2*w^3 + ... = (m-c0)

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

      We don't care about actual values of c0, c1 etc. We are just checking if a solution exists. It exists as long as there is a -1 <= c <= 1 such that m-c is divisible by w and (m-c)/w can also be formed by the weights.

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

        That's what I want to ask why (m-c)/w should be again equal c0+ c1*w^1 + c2*w^2 + ...
        Please forgive me if it's a dumb question

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

          you call the function trysolve thrice with m,m+1,m-1(possible options of c0) now int that function you first check if the number that you received (ie m or m+1 or m-1) is divisible by w ,if it is you divide it by w and again call the function with the quotient ie (m-c0)/w so now the situaution is c2*w^2+c3*w^3... = (m-c0)/w-c1 ,at each step you'll have three choices for c1,c2...(-1,0,1 ie adding it on left/rigth or not adding it at all) if by subtracting any of these you can make the variable exactly divisible by w you choose that path if thus proceeding you reach the base state m=1 you get the answer as true. hope i made it clear :)

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

    wonderful to solve this problem,easy to understand

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

    Thanks for the great explanation! It should be in the editorial.

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

    A beautiful solution...

    Loved your explanation

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

    Nice, really clean solution. Thanks a lot for the explanation :D

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

Я думаю, что в Е тоже ограничения заданы неправильно, так как у меня зашел квадрат — предпросчитаем префиксные и суффиксные ответы, дальше перебираем начало и последовательно добавляем элементы, модифицируя, если нужно, ответ

По решению из разбора — можно также предпросчитать префиксные и суффиксные ответы, и начинать идти только от элементов, перед которыми стоят *. Итого ассимптотика O(|S| * кол-во умножений)

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

    Поправьте меня если я не прав, вот такое решение за O(|S| + k^2), где k — кол-во умножений

    Как и в комменте выше, посчитаем префиксные и суффиксные ответы. Они покроют случаи, когда знак умножения стоит только с одной стороны от скобки. Перебираем пару знаков и находим ответ за O(1) с помощью предпросчитанных массивов и дополнительных, указывающих на произведение и длину цепи, идущей слева или справа.

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

In problem B, Why funtion pow() to find powers of 10 doesn't work right sometimes ? ...anyone? in my machine pow() worked well, but when sent to CF judge I receive WA. T_T.

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

    Same problem! I got 5 WA because of this :(

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

    it has to do with pow() returning a double type value. even i got a WA verdict due to this

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

      Use always ceil(pow(a,b))

      function.. because pow() returns double and its values is always some what less than anticipated.. eg pow(4,2) will be 15.9999999... so the int will override the value and save it as 15.. using ceil() its ceiling fuction and will solve your problem.. you can also use (pow(a,b)+0.01) because usually the remainder value is less than 0.01. see 11655937

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

for Problem D,I have subtracted triangles formed from collinear points from total no of triangles but still getting wa. please help .Here is my solution

http://codeforces.com/contest/552/submission/11656405

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

(For problem B)
why function pow() doesn't work right sometimes?
what should I do in case of finding power ?

Thank you.

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

    The problem with pow is that it returns a floating-point value and you are rounding it to an integer and losing precision. Implement your own exponentiation function using only integer variables and it should be fine.

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

А как может получиться ноль? "пытаемся отнять от него w" ... "Если этот разряд ... 0" Если он был [0..w-1] |-w => [-w..-1] как может быть 0?

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

C can also be solved with this simple approach :-

If m is a power of n then answer is "YES" otherwise check :-

In an array store values of powers of n such that values are less than m .. Also add m and a the power of n just greater than m.. (This is because higher powers of n will not be useful in contributing to the weight on either side !)..

Let elem be the count of elements in the array .. For ex- n=3 m=7, arr={1,3,7,9}; elem=4;

Then simply run a O(2^elem) recursive function to get the values of sum of all 2^elem possible subsets of the array ... If any of the sum (out of 2^elem) repeats then answer is "YES" otherwise "NO"..(It can easily be checked by using a map).

One of my friend Meintoo got it correct during the contest — his iterative solution

here's the link to my solution(after the contest) — recursive solution with comments

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

    Hey I thought of the exactly same approach during contest, but could not come to the conclusion that if ANY of the sum repeats then always answer is "YES" else "NO".

    can you please explain that?

    Thanks for sharing :)

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

      It is because every sum is a result of different subset so it is guaranteed that at least one element is different in the 2 subsets with same sum ..

      And now the catch point — no array for any n can have 2 subsets of equal sum if it has only increasing powers of n .. check it yourself 1,3,9,27 ... no two distinct subsets can b equal ... (holds for any n >=2).

      So if we are getting 2 subsets of equal sum then surely the number m is playing its role and is in one of the subset and not in other because its presence in both subsets create the same problem (no array with any n can have 2 subsets of equal sum if it has only increasing powers of n);

      So the deed is done .. m is in one of the subset and weights on its side include the numbers in the subset containing m and the other subset constitutes the weight on the other side .. Now in case u worry that same element may be present in both subsets then simply eliminate it(subsets will have same sum, then also) and m can't be in both subsets as stated above .

      Hope I explained clearly :)

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

        Okay.. I was actually trying to prove that no array trick mentioned by you, but wasn't sure if number m plays it's role in only one of the subsets.

        Thanks a lot for clarifying. :)

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

        thanks your approach was really nice.just one more thing would this have worked in case m & w could be of order 10^18? in case it wouldn't what should be the approach? thanks.

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

          No it won't work in that case . Because this solution is based on the face that for n==2 and n==3 the answer is always "YES". and for n>=4 we see that 10^9 < n^15( 4 <= n < inf) . So the 2^elem recursion is under time limit .. But for 10^18 it would be 10^18 < n^30 or so for 4<=n<inf and so our solution may get TLE ...

          Also another problem would be that the sum of subsets may exceed the range of long long(in c++).

          In case of n,m<=10^18 this solution may do fine ( i think so!!! ). I have added all the necessary comments in the solution. It's based on — wrick's solution ...

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

    nice explanation dextrous !!!

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

    I too got it accepted(during the contest) using the same concept.
    In case anyone wants to view the solution: http://codeforces.com/contest/552/submission/11647268

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

    Nice Approach .

    Thanks for sharing your solution .

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

    Why will the higher powers of n not be useful in contributing to the weight on the either side?

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

Wild_Hamster Many solution get AC below 3 sec.So TL 3 sec not enough to block the n^3/6 solutions.

UPD: Now I see some solution gets AC in 1.1 sec .

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

It was great contest especially the A,B and C problems can be solved in math ways :)

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

For problem D, I had a O(n*x[i]*y[i]) solution:

11646915

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

Can anyone explain me the solution of C 11641785 by I_love_Hoang_Yen , the attempt part and the prove that it will give correct answers?

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

Can you explain more in problem C. I am not getting when it is not 0/1 what are you saying. Plz explain something more means idea and concrete proof briefly

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

По-моему, задачу В проще решать рекурсией In my opinion, it is easier to solve B with recursion. http://codeforces.com/contest/552/submission/11638760

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

Unable to parse markup...

please fix this:) Wild_Hamster

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

Can someone please explain me why the time complexity of 552D for the solution mentioned is O(n^2*logn)?

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

    Well , i would try to explain my approach which is O(n^2*logn) .
    What I did is for each i , I calculated the slope of all lines taking ith one and all upto n . Then , total number of triangles having ith one as the vertex would be (n-i)C2 .. then i stored all the slopes in the map !! for all the lines having same slope , would not form a triangle , hence subtracted from the answer .
    thus it was a O(n^2*logn) approach !!! check 11649484 this for better understanding and tell me if not clear .

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

    n^2 for the nested loops and log(n) for the map used ...

    Yhis is in accordance with the solution given by Meintoo above ...

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

Could someone please share their/an implementation of the editorial for C? I am struggling to implement the idea.

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

Thanks for providing solutions but I think it makes more sense to actually submit them to CF instead of putting to ideone. In this case we will be able not only see the code but also see the time and memory consumed by your solutions (and their own output in case if multiple solutions are allowed).

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

hello in problem D , can anyone explain how to check the number of point that lay in each line in O(log(n)) thanks in advance

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

Java solution O(n^3) for problem D works :) 11671766

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

    Could you explain your code please? :) Any idea why my code is giving a TLE?

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

      From your code

      area(x1, y1, x2, y2, x3, y3) = x1 * det(y2, 1, y3, 1) — y1 * det(x2, 1, x3, 1) + det(x2, y2, x3, y3)

      So, area(x1, y1, x2, y2, x3, y3) = x1 * y2 — x1 * y3 — x2 * y1 + x3 * y1 + x2 * y3 — x3 * y2 = (x2 — x1) * y3 — (y2 — y1) * x3 + x1 * y2 — x2 * y1

      Let a = x2 — x1, b = y2 — y1, v = x2 * y1 — x1 * y2 (or v = a * y1 — b * x1). We may not calculate these values everytime in inner loop.

      area(x1, y1, x2, y2, x3, y3) != 0, so a * y3 — b * x3 != v

      There are a lot of operations (additions and multiplications) in inner loop, so your code is giving TLE.

      P.S. Sorry if my English is bad.

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

Can someone explain me this code for Problem D : http://codeforces.com/contest/552/submission/11636769

I know that he is calculating the equation of the line .. But how trip (variable) is working here and also about ans -= trip/3 .... Thanks in advance :)

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

    Considering each point as a starting point he is iterating through all the second points to define the line that he would be considering. tp defines the equation of the line that he is considering and cnt[tp] the number of ending points considered till now that give the equation tp for the given starting point.

    Let L be the set of line equations for the given starting point.

    Notice how he does trip +  = cnt[tp] before incrementing the value of cnt[tp].

    So for each starting point he actually adds the value to the variable trip.

    That is the same as adding

    Okay so he has considered all the collinear triangles that he could have made. However, he has overcounted a little as he has counted a collinear triangle of the form: A – B – C thrice because he has counted this triangle once with A as a starting point, then B as a starting point and C as a starting point . So trip should be divided by 3 .


    Obviously

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

Zlobobers code for problem D gives compilation error on ideone

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

Can somebody explain why the complexity of E was O(|s|*17^2) !

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

    It is given that max number of  *  signs are 15. In the editorial solution we are appending a 1 *  at the beginning of the expression and a  * 1 after the expression as that won't change the result. So the the number of  *  signs can be 17 now.

    Then the code is something like this:

    for open_bracket from 0 to pos[*].size()-1{     //17 times at max
            for close_bracket from pos[*][open_bracket]+1 to pos[*].size(){   //17 times at max
                 evaluate the expression with the given brackets    //O(|S|)      
            }
    }
    
    
»
9 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Hi everyone,

I'm trying to understand problem D (Vanya and Triangles) but I really can't get it. What does it mean "If some line includes x points, then in fact we counted, that it has 2 * x * (x - 1) points, because we included each point 2*(x-1) times in this line."?

I've tried looking at this solution http://codeforces.com/contest/552/submission/11663734 and I kind of get what he did even if it's not clear what exactly the normalize table does for me.

Can someone explain me more clearly?

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

    For each pair of points get the equation of line (ax + by + c = 0, make sure a, b, c are coprime, i.e. convert 2x + 2y + 2 = 0 to x + y + 1 = 0). Now map this line with these 2 points. After processing all the points, if some line actually contains K points, we would have added 2*K*(K-1) points since we were processing each pair of points. We could have used a set to store the K points but that would add an extra log factor. Code

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

      but in your code, you checked i*(i-1)==no.of points, doesn't it be 2*i*(i-1) ??

      for (int i = 1; i <= n; ++i) { if(i * (i — 1) == points) { point_cnt = i; break; } } ans -= nc3(point_cnt);

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

        Sorry for the confusion, my implementation is a bit different from the explanation. It's because I didn't use all n x n pairs of points to create lines, I only used C(n, 2) pairs. Check this part:

        for (int i = 0; i < n; ++i) {
        	for (int j = i + 1; j < n; ++j) {
        		line l = get_line(p[i], p[j]);
        		lines[l] += 2;
        	}
        }
        

        In this case, if a line contains k collinear points, there are C(k, 2) ways of choosing a pair of points and for each of these pairs, 2 gets added. So, in total, we have 2 * C(k, 2) instead of k. Hope it is clear now.

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

I ways get a wrong answer on case 41 in problem E ,can anyone help me to check my program. http://codeforces.com/contest/552/submission/11986906

Thank you :)

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

how can E be done by brute force?

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

Прочитал разбор после виртуалки, ради интереса написал Д за куб. Так оно работает быстрее чем n2logn с map!!

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

Man I can't understand a thing from those solutions, this editorial should be way more clear

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

Can someone please explain me how to turn some value into a w-ary representation? Because as I know it's always possible to turn any number to only BinaryRepresentation, sorry for my English if there're some mistakes. Thanks in advance!

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

I solved C a bit differently. Looks like it isn't mentioned in the comments. Apologies if I missed it. So if n = 2 the answer always exists. From n = 3 let's find the sums of all possible subsets of (w^1, w^2, w^3, ...). We only need at most 20 because after that it exceeds 10^9. (This limitation is actually a bit more complicated than that but let's assume it works). Because there are only 20 of these values, one can generate sums for 2^20 subsets within the time limit. If m is present in one of these sums, then the answer is YES. Or if the difference of sums for two subsets is m, the answer is YES. One additional condition to look for is that the subsets must be disjoint. Because you can't have the same weight in both the pans. So for each sum in the found sums array, check if a subset with sum = m - sum[i] exists and see that position_of_found_sum & i is 0 (disjointness).

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

C is awesome!! Loved it