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

Автор fcspartakm, 11 лет назад, По-русски

557A — Илья и дипломы

Данную задачу можно решать несколькими способами, рассмотрим один из них — разбор случаев.

Если max1 + min2 + min3 ≤ n, тогда оптимальный ответ (n - min2 - min3, min2, min3).

Иначе, если max1 + max2 + min3 ≤ n, тогда оптимальный ответ (max1, n - max1 - min3, min3).

Иначе, оптимальный ответ (max1, max2, n - max1 - max2).

Данное решение верно, так как по условию задачи гарантируется, что min1 + min2 + min3 ≤ n ≤ max1 + max2 + max3.

Асимптотика решения — O(1).

557B — Паша и чай

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

Сначала отсортируем все чашки по неубыванию их объемов. В силу жадных соображений верно, что отсортированные чашки с номерами от 1 до n будут отданы девочкам, а с номерами от n + 1 до 2 * n будут отданы мальчикам.

Теперь сделаем бинарный поиск с итерациями по объему чая, который будет налит каждой девочке. Пусть на текущей итерации (lf + rg) / 2 = mid. Тогда, если для всех i от 1 до n верно, что mid ≤ ai, а для всех i от n + 1 до 2 * n верно, что 2 * mid ≤ ai, тогда нужно поднять нижнюю границу бинарного поиска, то есть lf = mid. Иначе, нужно опустить верхнюю границу бинарного поиска, то есть rg = mid.

Асимптотика решения — O(n * log(n)), где n — количество чашек.

557C — Артур и стол

Данная задача решается следующим образом. Изначально, отсортируем все ножки по неубыванию их длин. Также нам понадобится массив cnt[].

Переберем длину ножек, на которых будет стоять стол, начиная с наименьшей. Пусть она равна maxlen. Количество единиц энергии, которое нам для этого потребуется будем хранить в переменной cur.

Очевидно, что необходимо открутить все ножки с длинами большими maxlen. Так как массив отсортирован, то, чтобы посчитать количество единиц энергии, которое понадобится для этого, можно воспользоваться суммой энергии на суффиксах. Прибавим это количество к cur.

Если количество ножек длины maxlen не строго больше количества оставшихся ножек, нужно открутить сколько то ножек с длиной меньшей, чем maxlen. Для этого воспользуемся массивом cnt[]. В cnt[i] будем хранить количество ножек со сложностью откручивания равной i. В нем будет содержаться информация о уже рассмотренных ножках.

Будем перебирать сложность откручивания от единицы и откручивать ножки с такими сложностями (прибавляя эти сложности в переменную cur), пока количество ножек с длиной maxlen не станет строго больше количества оставшихся ножек.

Когда ножек длины maxlen станет строго больше половины оставшихся ножек обновим переменной cur ответ.

Асимптотика решения — O(n * d), где n — количество ножек, а d — разность между максимальным и минимальным количеством единиц энергии, которое может понадобится, чтобы открутить какие-то ножки.

557D — Виталий и цикл

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

Ответ на задачу равен трем в том случае, когда в графе нет ни одного ребра. Тогда количество способов добавить три ребра в граф, чтобы получился цикл нечетной длины равно количеству способов выбрать три вершины из n (будем соединять ребрами именно эти вершины). Это число равно n * (n - 1) * (n - 2) / 6.

Ответ на задачу равен двум, если в графе нет компонент связности с количеством вершин большим чем два. Как найти количество способов?

Пусть cnt2 — количество компонент связности, которые состоят из двух вершин. Тогда выберем любые две вершины, соединенные ребром. Эти две вершины и ребро, соединяющее их точно войдут в ответ. Осталось выбрать любую другую вершину и соединить ее двумя ребрами с выбранными ранее соединенными вершинами. То есть количество способов равно cnt2 * (n - 2).

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

Пусть в поиске в глубину мы идем из вершины v в вершину to (вершина v уже точно покрашена в какой-то цвет). Если вершина to не покрашена, тогда покрасим ее в цвет, противоположный цвету вершины v и запустим поиск в глубину от вершины to. Если вершина to уже покрашена в цвет, не равный цвету вершины v, пропустим ее. Если же color[v] = color[to], тогда выведем "0 1" и закончим алгоритм. Это означает то, что в графе уже есть цикл нечетной длины.

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

Если в текущей компоненте связности cnt1 вершин в одной доле и cnt2 вершин в другой доле, тогда к количеству способов нужно прибавить cnt1 * (cnt1 - 1) / 2 и cnt2 * (cnt2 - 1) / 2.

Асимптотика решения — O(n + m), где n — количество вершин в графе, а m — количество ребер.

557E — Аня и полупалиндром

Данная задача решается с помощью динамического программирования.

Сначала насчитаем матрицу good[][]. В good[i][j] запишем true, если подстрока с позиции i до позиции j полупалиндром. Иначе запишем в good[i][j]false. Это можно сделать, перебирая "середину" полупалиндрома и расширяя ее влево и вправо. Возможны 4 случая "середины", но опустим их, так как они достаточно просты.

Теперь будем складывать в бор суффиксы заданной строки. Также будем хранить массив cnt[]. В cnt[v] будем хранить сколько полупалиндромов заканчивается в вершине бора v. Пусть сейчас мы записываем в бор суффикс, который начинается в позиции i, кладем символ, стоящий в строке в позиции j, и переходим в вершину v. Тогда, если good[i][j] = true, нужно сделать cnt[v] +  + .

Теперь простым обходом в глубину посчитаем для каждoй вершины sum[v] — сумму чисел, стоящих в вершине v и во всех ее поддеревьях.

Осталось только восстановить ответ. Запустимся из корня бора. Будем хранить его в строке ans. В переменной k храним номер искомой подстроки. Пусть сейчас мы стоим в вершине v, по символу 'a' можем перейти в вершину toa, а по символу 'b' — в вершину tob.

Тогда, если sum[toa] ≤ k, сделаем ans +  = 'a' и перейдем в вершину toa. Иначе, нужно сделать следующее: k = sum[toa], ans +  = 'b' и перейдем в вершину tob.

Когда k станет  ≤ 0 выведем получившуюся строку ans и закончим алгоритм.

Асимптотика решения — O(szalph * n2), где szalph — размер входного алфавита (в данной задаче он равен двум), а n — длина заданной строки.

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

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

You have some Russian (I guess) in "557C — Arthur and Table" 's description.

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

Taking min of 3 values sounds easier than doing bin.search in B:)

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

Недосообразил в задаче D, как найти кол-во способов, если ответ надо добавить 2 ребра. Все моральные свои силы я истратил на задачу C. Обидно:)

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

wow what a quick editorial compared to the last one :) some statements (in problem C editorial) is still in russian..

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

Can someone please explain C in more details?

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

    Basically you have to ensure that in remaining legs, frequency of the maximum element is greater than half of number of remaining legs.

    We can do this by first choosing the value of maximum element(of remaining legs ). In order to ensure that this is indeed the maximum, we remove all the legs whose length is greater than this value.

    After that,we also have to ensure that frequency of the maximum element is greater than half of number of remaining legs. To do this, we remove appropriate number of legs whose length is less than this decided value.

    For a given choice of value of maximum element, we can calculate the energy in O(200) by just maintaining the frequency of energy required to remove the legs.

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

quickest editorial ever :)

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

quickest editorial ever

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

Problem statement was not very good. :(

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

so the array size is the silliest mistake in history, Why the hell did I get TLE instead of RTE for this code !!

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

F*king precision error!!

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

This is how I solved D.
1st thing to notice was that only 3 edges are sufficient to create an odd cycle.
Case 1: Edges needed 0. Just check if a graph (every component) is bipartite or not. If it is not than the graph contains odd cycle. Ans is (0, 1).
Case 2: Edges needed 1. For this case color every component with 2 colors. Lets say we use A, B to color the nodes. If two nodes have same color than we can add edge between them to create an odd cycle. So ans for this case is (1, naC2 + nbC2) where na is the no.of nodes with color A and nb is the no of nodes with color B. We need to sum this for all components.
Case 3: Edges needed 2. For this case do dfs to count no of components of size 2 and size 1. Ans for this case is (2, 4 * two_cntC2 + two_cnt * (n — 2 * two_cnt)). Every two components of size 2 gives 4 different ways. We also add the ans for the case where individual node components are present which is basically equal to two_cnt * (n — 2 * two_cnt).
Case 4: Edges needed 3. That is every node is disjoint. Ans is (3, nC3).

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

Second problem was wrong because of a single word; :(

It must have been,

cout<<fixed<<answer; instead of cout<<answer;

used it after contest and got accepted. :(

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

This is just wrong, my submission for B during the contest 11860848

And after the contest the same code along with fast IO 11867502

I spent about an hour trying to debug my solution when there was nothing wrong. Isn't CF supposed to be non-IO centric. This is unfair, Binary search timing out due to Fast IO.

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

C can be solved by treap and the asymptotic will be O(nlogn). This solution doesn't demand constrains on lengths and energy.

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

Can anyone Explain why this code give me WA on test case 8 ?! 11861412

how can I edit it?

thanks in advance.

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

Can anyone explain why this code 11861412 give me WA on test case 8 [problem B] ? and how can I repair it?

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

    Maybe because you just checked if you could put "2 * qua" for boys. You didn't check if you could put "qua" for girls... That's the same mistake I've made... You have to check it because it could happen that you can put 2 * qua for boys, but the smallest cup doesn't support qua ml of water.

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

Также нам понадобится массив cnt[]. Спасибо за быстрый разбор, но читается это с трудом. Сразу в голове возникает куча вопросов "Какой кнт, зачем кнт, что это за кнт массив?"

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

Problem E can be solved in O(n2) time. You can read my solution (11862688) if you interested in. (I've used that alphabet size is equal to 2, but it is easy to fix it)

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

Have you any time to debug my Error. Why my code gives wrong ans ? (http://mirror.codeforces.com/contest/557/submission/11868836)

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

Hash can be used to find if a substring from index i to j is half palindrome or not.

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

Hash can be also used to find if a substring from i to j is half palindrome or not.

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

Well, I solved problem C a little differently.

First we sort the legs by their lengths in ascending order (the energy values don't matter). Then we split the sorted list into blocks, where the legs in the same block have the same length.

length: 1 1  2 2  6 6 6
energy: 5 5  4 8  2 3 3

After that we iterate over every block. In iteration i, we try to find the answer when the legs in block i are the longest remaining.

In iteration i, obviously, all legs in block i must be kept in order to find the optimal answer. And we must remove all legs in blocks from i + 1 to block-count (since legs in block i are the longest remaining), and keep at most block[i].size - 1 legs in blocks from 1 to i — 1 (to keep the table stable). Therefore the answer equals to
total energy of block (i + 1)~block_count + total energy of block 1~(i - 1)total energy of the (block[i].size - 1) largest elements in block 1~(i - 1).

For the first and second part we can either use partial sums or calculate while iterating. For the third part, we can use a std::multiset to store all previous legs' energy values. For any k, the k largest elements can be accessed by just iterating k times in the multiset. Asymptotic time complexity is... , I think?

My code (written rapidly during the contest and may not be so elegant): 11859771

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

I have changed the type of array c ( 11867935 ) to long long and the code gets Accepted (11868444)! Can anyone explain why?

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

I'm wondering why this submission got TLE for problem B. I believe the complexity of this solution is also .

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

Please improve the English translation

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

Can someone, please, tell me what's wrong with my code for C? It gives correct answer with all the small cases so I cannot debug it. At least some test case that won't pass with it.

I wrote a lot of comments to make it easy to understand: http://mirror.codeforces.com/contest/557/submission/11870567

The idea is basically the same as the author:

  1. Precalculate cost of removing all legs of larger size
  2. Iterate over each leg size, removing larger ones in O(1)
  3. Keep a Priority Queue with the legs of lower size to obtain the largest ones in lg(n)
  4. Obtain from the priority queue a number of legs strictly lower than the number of legs of the current size (which won't be deleted)
  5. Minimum Energy Used = min(currentMin, energy of larger + energy of lower — energy of non-removed legs

Thank you very much in advance!

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

Who can explain me why the compiler reterning wrong answer to this example: 500*3*71199.
This will be 106798500, but it says that my programm reterns 106799000 even with this if (n == 71199) cout << 500.0*71199.0*3.0 << endl;
The submission: 11870868

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

can you please provide codes ?

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

In second question B --> we can do without binary search ie just be greedy :)

We can even do it more simplified as let say g=a[1] and b=a[n+1] (after sorting 1 based index) then just have 2 conditions if tc = (b*0.5*n+b*n) --> b*0.5 maximum girl cup can have condition being b*0.5 <=g if not so then directly (g*n+2*g*n) is the answer. for case when ans>w take ans=w. that's it :) Here's my AC code — http://ideone.com/1POnoF

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

http://paste.ubuntu.com/11801550/

I'm getting TLE in E problem. i have a matrix named pal. pal[i][j] = 1 means substring that starting from i and length is j is half palindrom.

i calculate matrix with complexity n^2 and then i find what string is.

i do that with three vector. i wont explain more. i think code is clear.

but the problem is why i am getting TLE ? can anyone tell ?

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

I solved C in O (N log N ). Here is the algo :

1) In a multi set (or any bst like structure) , store all the legs with their energies as < length, energy >, call this as M. Let total weight of all legs be TOT.

2) For all distinct lengths in this map , assume that the table is going to be built with this length as maximum length, call this length L. Let there be total of CNT number of these legs with length L. Now what you need to find is CNT-1 legs with max energy and length less than L. This can be done using a multiset for energies — once you have crossed a length, you insert all the different energies for this length into it, call this multi set as W.

3) Find the net energy value of all legs of this table = ET and update answer with ans = min(ans,TOT-ET).

Complexity analysis : 1) Creation of M = O (N log N)
2) Finding CNT for all distinct lengths — O(N)
3) Creation of W = O(N log N)
4) Selecting CNT — 1 legs of max weight from W = O (N)
Because worst case, we can have sqrt N distinct lengths occuring sqrt N times and so we will have to go through sqrt N max energy legs for each of the sqrt n lengths = O(sqrt n * sqrt n) = O(n)

Soln link — http://mirror.codeforces.com/contest/557/submission/11872727
PS : During contest, in the last while loop, I wrote "it1" as "it" and unfortunately "it" was also a variable in that scope so that caused WA on some pretest. Silly typo :\

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

I am new here. What should I do if I cant understand the solutions even after reading the editorials? Any tips?

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

    You can take a look at others' code, which you can find by clicking the numbers like 'x2917' on the 'PROBLEMS' page. If you don't know an algorithm mentioned in the editorial, search for it on the Internet. If these still don't help, directly commenting under the editorial asking for help is another way. When doing this, details such as which problem and where you didn't understand (or even better, which sentence) are necessary.

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

fcspartakm, I understand both solutions, greedy and bs, but I always had a doubt in binary search with limits of type double. Can you give any tips, did not submit to the binary search but understood perfectly, the only question is in the loop breaks.
For example: l=min of search, r=max of search, EPS=1e-6 how shall I compare them to complete the search? so? l-r<EPS
I wanted to know, as they do this test? or rather, what better way to do it?

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

Thanks for the interesting problems :)

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

For Problem C Can anyone please let me know why i am getting WA for the first test case while the code is running fine on my system atleast for the first three cases.11875338

I am maintaining a set for the table lengths'(st) and another set to store the energy levels for a particular length(pq[]). The array cnt[] stores the number of occurrences for a particular length.

The loop basically tests for three possibilities.

temp=n
while(temp>2){
it=st.end();
if(cnt[*it]>temp/2)   //temp is used to store the current number of legs
   print ans

else if(cnt[*it]==temp/2)
   //find a length<*it with the minimum most value for energy to be incremented to answer.
   //let this be denoted by len
   print ans+len

else
   //increment the ans with all the energy levels that correspond to the current length
   temp-=cnt[*it]; //decrement the current list of legs
   it2=pq[*it].begin()
   while(it2!=pq[*it2.end())
      ans+=*it2;
      it2++;
st.erase(it);
}
  
   
  • »
    »
    11 лет назад, скрыть # ^ |
     
    Проголосовать: нравится 0 Проголосовать: не нравится

    ->set::iterator it,
    ->pq[*it]
    ->cnt[*it] Are they not contradicting? I don't know but can you use iterators of different types invariably?

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

      *it dereferences the iterator, so it's simply an int. However, st.end() is NOT the iterator for the last element — it actually points beyond the end of the set, so you can't dereference it. You need to decrement it by one (--st.end()). In other containers like a vector you can use back(), but there is no such method in a set.

      However, that block isn't reached in the first test case anyway. You didn't initialize mini, so if it starts out as zero in GCC, you will get zero as your answer. In VS it starts out as -858993460, which is even worse.

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

Задачу С думал так же решать,как и в разборе,но испугался ограничений на время (1с). Подскажите, каким образом решение O(n*d+n*logn) может пройти на Free Pascal за 1с? Насколько мне известно (опыт+инфа) 10^6 итераций ~1 сек.

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

    Какой-то странный у тебя опыт (инфа)

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

    На Сodeforces достаточно хорошие машины, и решение за 10^8, иногда даже 10^9 но с маленькой константой отлично заходят на ура. Да и вообще на любых олимпиадах 1 секунду можно расценивать как 10^7-10^8, исключение — медленные языки программирования.

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

      Спасибо. Просто давно интересовался временем работы. Я,кроме Pascal,больше не пишу ни на чем. А на Pascal решения видимо работают много медленнее

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

After I read the editorial, problem A is much easier than I think :((

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

Thanks for the editorial. First problem could also be solved with complexity o(max(max1-min1,max2-min2,max3-min3)). My friend submitted using this method and got accepted. But since we can solve it with o(1) like in the editorial I think that solution is kinda slow.

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

Now we need to use dfs and try to split every component in two part

Can someone explain this part of problem D?

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

In 557B — Pasha and Tea party what is "lf" and "rg"?

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

    Binary search boundaries (the range in which we know the answer should be). lf is initially 0, and rg is initially w. On every iteration, we split the range into two halves, and choose which one of them is correct. Eventually the range will become small enough that we can print the answer.

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

      I implemented following: lf=0 rg=w/3*n While(lf<rf) { mid=(lf+rg)/2; if(mid<= a[0] && mid*2 <= a[n]) lf=mid Else rg=mid }

      wheree a is sorted array of cup capacity And this loop doesn't terminate.

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

        Always use fixed number of iterations in binary search on doubles. I usually use 150-200 iterations and everything works.

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

          Does it work for all cases irrespective of size of input? BTW is my implementation correct apart from correction you suggested?

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

            If you can represent left and right bounds using doubles — than the answer is yes, but I don't remember the reasoning of this. Maybe someone can elaborate this?

            rg=w/(3*n) — you should use parenthesis here

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

          150-200 is a way too much, considering doubles only have 52 significant bits. Unless the interval converges to zero, the last 100-150 iterations will do nothing.

          In fact, you can do while (x != y) and it will do 50-60 iterations in most cases — except when the answer is zero, in which case it can do about a 1000 iterations. Of course, you shouldn't do that because you're likely to run into the same problem as with int binsearch — when x and y are the closest possible numbers, (x+y)/2 will be equal to either x or y, and if you guess "incorrectly", you will get an infinite loop. You could fix it by using std::nextafter (i.e. if you know that the answer for m is no, then technically you need to set y to the number just below m, or std::nextafter(m, l)), but that's not pretty.

          Not to mention that this problem doesn't need binary search anyway :(

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

You have mistake in Problem A: Not <=, it will be right if write >= !

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

Why doesn't the tutorial appear with the problem statements? Would I always have to navigate to the blog to see the editorial? How come some contests have tutorials appearing with each problem statement?

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

Why TLE O (700) ? 11885455

UPD: because of double with cin :( 11885605

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

For 557C, we can use the same idea to find the solution without too much thing to compute.

The idea is (reiterating author's approach): Let's say we want to keep legs with length k. All legs length greater than k must be removed (otherwise k is not the maximum), the remaining is to make sure removal of legs length less than k requires minimal energy.

Observation: If there are P legs whose lengths are less than k, and there are Q legs with length k. You need to remove at least P - Q + 1 legs whose lengths are less than k to make the table stable.

Observation: By above, you need to keep at most Q - 1 legs whose lengths are less than k to make the table stable. Otherwise, there are at least Q non k-legs with Q k-legs, and k-legs is obviously not the majority. Table is not stable.

Observation: Remove legs with minimal energy is equivalent to keep legs with maximal energy.

So, you need to compute two things: total energy to remove (now means keep) k-legs, number of k-legs. Enumerate all possible maximal k, get the keep energy for k-legs, plus get the sum of the largest Q - 1 energies of legs whose length is less than k. The way to do it is similar to the O(nd) approach described by author, but we take the exact opposite values. Find the maximum values among all choices of k, get the answer by total energy — this max energy.

Doing so does not require suffix sum.

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

We check at a node if sum[toa] <= k.

Let us say sum[toa] is less than or equal to k. Then we go to node toa, now, for all nodes sum[toa from new node] will also always be less than k.

So, in such a case k will never become less than or equal to zero.

The how will the algorithm terminate?

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

    Typo, it should be sum[toa] >= k

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

      There is one more missing thing. Once we reach a particular node $$$v$$$ while constructing the answer, we must also subtract $$$cnt[v]$$$ from $$$k$$$ to account for half-palindromes ending at the node $$$v$$$. So, if $$$sum[to_a] \ge k$$$, we move towards $$$to_a$$$ and also update $$$k$$$ as $$$ k$$$ $$$-= cnt[to_a]$$$. Otherwise, we move towards $$$to_b$$$ and update $$$k$$$ as $$$k$$$ $$$-= (sum[to_a] + cnt[to_b])$$$

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

I found the statement of the Problem A to be not clear. I could not understand the fact that if we already have max possible A diplomas, then try finding max possible B diplomas and further max possible C diplomas.

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

    My solution is a bit different from the author' solution:

    11892821

    Call t1, t2, t3 is the number of diplomas in first, second and third degree in the optimal answer. We know that t1+t2+t3 = n.

    Our goal is to maximize t1 first, then maximize t2. So we will first make t1 as large as possible. We knew that 't1 <= max1'. However, we'll need to take care about the fact that t2 >= min2 and t3 >= min3, too. So, we'll have n-t1 = t2+t3 >= min2+min3, which mean t1 <= n-min2-min3. Finally, we'll have t1 = min(max1, n-min2-min3).

    At this point, we'll have n := n-t1 diplomas left. Now, we will take do the similar thing again, make t2 as large as possible. We know that t2 <= max2 and t3 >= min3 <=> n-t2 >= min3 <=> t2 <= n-min3. So we'll have t2 = min(max2, n-min3).

    We now know the value of t1 and t2, so we also get the value of t3, which equal n-t1-t2.

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

For Problem D of the contest I have implemented the idea of DFS mentioned in the Editorial but i am still getting WA on the test 31. http://mirror.codeforces.com/contest/557/submission/11901124 I would be grateful if anyone could point out my mistake and point me in the right direction.

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

To solve B, I just needed to sort them and write only 2 lines and it's done, no need to iterate on any thing, the answer pops right up. My solution: 11927301 Complexity: O(n.log(n)) for the sorting

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

I was tricked by myself when I attempted to solve D.

The definition of odd cycle is obvious: Any graph that is not bi-colorable iff it has odd cycle (proof omitted). So if the graph has odd cycle it's done, we don't need to add any edge and this is the only way to achieve minimum (thus 0 1). Note that bicolorable graph is bipartite.

The solution remains to categorize answers for different class of bipartite graph. Note that you need at most 3 edges to form an odd cycle in any cases, so just think about when you need to answer 1, 2, and 3.

Case 1: when minimum = 3. It means you need to form a triangle by picking three vertices. This also means that there are no edges, thus maximum vertex degree = 0. In this case, answer is to pick any three vertices, which is .

Case 2: when minimum = 2. It means that no vertex has at least two edges (otherwise minimum = 1 by joining two vertices from the two edges to form a triangle). Which implies that maximum vertex degree = 1. To form a triangle, we must use any of such edge (u, v) and find other vertex w and use two edges to form a triangle. Note that since maximum degree = 1, all m edges are the required edge. So the answer is m × (n - 2) (for each edge, pick other vertices to form triangle).

Case 3: when minimum = 1. This means that maximum degree is at least 2. This is also where I got tricked. In this case, we don't just want to count number of ways to form triangle, since one can add an edge to form an odd cycle. Consider this: W-B-W-B-W, where W means a white vertex, B means a black vertex. One can add just on edge, that connects the first and the last W, to form an odd cycle with length 5. Given this, the answer is much simpler: notice that for any connected bipartite graph, connecting any two vertices of the same side breaks bipartite-ness, thus odd cycle exists. So the answer is simple: for each bipartite connected components, the answer for that component is the number of way to connect two vertices on the same side. Suppose the bipartite graph has U vertices on the left, V vertices on the right, the answer is .


Indeed, what if the problem is like: find the minimum number of edge added to form a triangle, and how many ways to do. When the graph is not bipartite, I think it requires matrix multiplication. If the graph is bipartite, the answer remains the same when the minimum edge added is 3 or 2. When minimum edge added is 1, I can't come up of anything that is faster than O(n2).

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

We can use dp for checking half-palindromes.

Suppose our good[][] array works correctly for substrings of length 1,2,3...i-1 Now we have to consider the substrings of length i and update the good[][] array.

It's obvious that good[i][j] = 1 if and only if,
- char at position i equals char at position j and
- (i+2 > j-2) or (dp[i+2][j-2] == 1)

Link

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

Ребят, я новичок, у меня возникли трудности по задаче B, не совсем понимаю, как реализовать бинарный поиск с итерациями в данном случае, не мог бы кто-нибудь показать код программы по аналогии с алгоритмом, приведенным выше. C++ или Паскаль (желательно паскаль)

Hi, Im beginner and i have any problems in 557B. I dont understand how to realize this example, exactly this example. I want to see code for this algorithm, с++ or Pascal (desirable Pascal), sorry for my very bad English

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

    Привет, в этой задаче бинпоиском нужно искать ответ, если он слишком большой, то сдвинем правую границу, иначе левую. Также стоит отметить, что поиск у нас вещественный, и чтобы не было проблем с точностью вместо условия в while(r — l > eps), где eps = 10^-7, проделываем итерации 1000 раз, while(q > 0), где q = 1000. Вот отрывок кода на c++. d — минимальная чашка у девочек, m1 — минимальная чашка у мальчиков, w — сколько всего чая в чайнике.

    int main(){
        long double l = 0, r = d + eps, m;
        int q = 1000000;
        while (q){
        	m = (r + l) / 2;
        	if (m > d + eps || m * n + m * n * 2 > w + eps || m * 2 > m1 + eps){
        		r = m;
        	}
        	else{
        		l = m;
        	}
        	q--;
        }
        cout << fixed << setprecision(6);
        cout << l * n + l * n * 2;
        return 0;
    }
    
»
11 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

I think the solution of problem A is probably wrong.
Like for the first condition max1 + min2 + min3 ≤ n, which means n - min2 - min3 ≥ max1.
And it saids the optimal solution is (n - min2 - min3, min2, min3), which actually invalid.

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

I have a O(N^2 + N^2 log N + N^2) solution for problem E.

Firstly, finding all the half-palindromes by O(N^2) brute-force. Then, sorting all the suffix by their indices with O(N log N) algorithm. In fact, it can be optimized by using suffix array algorithm, and this will come up with an totally O(N^2) algorithm for this problem. Finally, sweeping the suffixes for counting the k-th sub-string in O(N^2).

And this is not depended on the number of kinds of alphas in the string. :) I don't know if my solution is strictly right, so comments are welcome. 11894668

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

Can anyone, please, explain Problem E ?

With all due respect, the explanation offered in this editorial is not clear at all.

I understand the part where we determine which substrings are half-palindromes as I did myself but I don't get the part where I'd have to use a trie. I tried to use a trie by myself but I think it's O(n3) .

It would be really nice if someone explains the approach of this editorial!

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

How to solve C if 1 <  = di <  = 105?

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

Can anybody give the the idea of Div 2 C, when the range of di can be anything and not just 1 ≤ di ≤ 200

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

    My approach have time complexity is O(N(logN)2), which not depend on value of di.

    First of all, I sort the array with depend in l[i]. Second, sort the array with depend on d[i]. Now for each leg, we know the ordinal of their energy units. For example, in test case 3, our sorted array (called a[]) and the ordinal of their energy units (called c[]):

    a[] = [1, 1, 2, 2, 3, 3]
    c[] = [5, 6, 3, 4, 1, 2]

    So we now, for the $i$-th leg, we have greedy approach: If we choose to use this leg, then we will use all of the legs that have the same value of length with this chosen leg. Call the number of legs that have the same length with i-th leg is k. The enery when we chose i-th leg is sum enery units of all the leg have greater length and sum of the i - (2k - 1) smallest enery units leg of which length is strictly smaller than i-th leg.

    Because all table must have more than a half legs of greatest length, so is we choose i-th leg is greatest length, the maximal numbers of legs that a table could have is 2k - 1 legs. To make i-th leg is the greatest length's leg, then we need to remove all the legs have greater length and take no more than k - 1 legs have smaller length. At the moment, we have i legs with have not greater than i leg, so greedily, we just need to remove i - (2k - 1) legs that have smallest enery units.

    Now, for each leg, we could easily use prefix sum to find sum of all the legs have greater length than our chosen leg's length. However, the harder problem is find the sum of i - (2k - 1) smallest leg's enery units. Remember about the array c[], which we store the ordinal number of the leg's enery units. Now, after attempt the i-th leg, we will knows that it exist the c[i]-th smallest enery units value.

    For example, when we check the 4-th leg (base on array a[]), we will have these valid enery units values [0, 0, 1, 1, 1, 1]. As we want to find sum of i - (2k - 1) = 4 - (2 * 2 - 1) = 1 smallest value, so we will find sum of 1-th smallest enery units, in this case is 3.

    Also notice that, the numbers of valid enery units values from 1 to j is always not less than the numbers of valid enery units values from 1 to i which i > j. So we could use binary seach to find the smaller number x that from 1 to x we can find i - (2k - 1) valid value. To do each of this operation in O(logN), we could use Fenwich or Segment Tree. After found the result x, our answer in case we use the i-th leg is sumLengthSmallestValidValue(1, x)+sumLength(i+1, n).

    In the other hand, to make sure that we just find the sum of the smallest enery units legs which have length strictly less than our chosen leg's length, after we check all the same length legs, then we update, not update for each leg (we could use stack or queue to solve that — if the i-th leg is diffence than the i - 1-th leg, than we update all the legs that stored in the queue now, other wise, if the i-th leg is same as the i - 1-th leg, push i to the queue).

    Here is my code which uses Segment tree: 23901663. So the time complexity is O(N(logN)2) due to using binary search on Segment tree for each leg. This is the first time I write the solution, so sorry for my bad idea's expression. Feel free for asking me any question, I will trying my best to explain :D.

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

In the guide of 557A, comparison symbols of the first two conditions seem wrong. '<=' should be replaced with '>=' i guess.

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

Problem C — Arthur and table can be solved in O(n*logn*logn) using fenwick tree, so even if difference in maximal and minimal energy is large,the solution will pass.
Here's my submission link : https://mirror.codeforces.com/contest/557/submission/92999357

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

in problem b (Pasha and Tea) i used binary search to solve problem but in this solution it get TLE but this solution accepts ,i used 10**-10 as epsilon in first solution and 10**-6 as epsilon in second solution . can someone explain why this happen in two epsilon please??

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

in problem B, i used binary search but in first solution it get TLE and it use 10**-10 as epsilon.

in second solution it accepts and it use 10**-6 as epsilon , can any one explain this two cases with different epsilon??