Блог пользователя A.K.Goharshady

Автор A.K.Goharshady, 11 лет назад, По-английски

Hi, Here's the editorial.

Please note that not all the codes presented below belong to me. (It's a combination of codes from our problemsetters and testers) -- And I borrowed AKGMA's account since I wasn't able to link to my own submissions somehow!

Note: It seems that the Codeforces mark-up is not functioning. To see a submission go to: http://www.codeforces.com/contest/282/submission/submission-number

A: Bit++

Just use a simple loop. (Take a look at the Python code)

GNU C++: 3314442, 3314464

GNU C: 3314471

Python: 3314475

B: Painting Eggs

This one can be solved by a greedy algorithm. Start from the 1st egg and each time give the egg to A if and only if giving it to A doesn't make the difference > 500, otherwise give it to G.

To prove the correctness, one can use induction. The base case is trivial. Suppose that we've assigned the first n - 1 eggs such that the total money given to A is Sa and total money given to G is Sg. We can assume Sa ≥ Sg. Now we must either add gn to Sg or add an to Sa. If we can't add gn to Sg, then Sg + gn > Sa + 500, so  - 500 > Sa - Sg - gn, adding 1000 to both sides gives us the inequality 500 > Sa + (1000 - gn) - Sg which is exactly what we need to make sure that we can add an = 1000 - gn to Sa.

GNU C++: 3314480, 3314484

GNU C: 3314488

Python: 3314492

C: XOR and OR

First of all, check the length of the two strings to be equal. Then with a little try and guess, you can find out that the zero string (00...0) can't be converted to anything else and nothing else can be converted to zero. All other conversions are possible.

GNU C++: 3314503, 3314504, 3314509, 3314512, 3314514

D: Yet another Number Game

For n=1, everything is clear. If a1 = 0 then BitAryo wins, otherwise BitLGM is the winner.

For n=2: define win[i][j] = (Whether i,j is a Winning position). It's easy to calculate win[i][j] for all i and j, using a loop (Checking all possible moves). This leads us to an O(n3) solution.

For n=3: Everything is similar to NIM, With the same statement of proof as for NIM, i,j,k is a winning position if and only if (i xor j xor k)  ≠ 0.[Don't forget the parentheses in code :) ] Complexity: O(1)

One can also solve this case using DP. We define lose[i][j]= (Least k, such that i,j,k is a losing position) ,lose2[i][j]=(Least k, such that k,k+i,k+i+j is a losing position) and win[i][j][k] just as the case with n=2. As in the codes below, one can calculate all these values in O(n3).

Using the same DP strategy for n=2 and the O(1) algorithm for n=3 and n=1, leads us to a total complexity of O(n2) which was not necessary in this contest.

GNU C++: 3314578, 3314580, 3314585, 3314588

E: Sausage Maximization

Can be solved using a trie in O(n log (max{ai})).

Start with a prefix of size n, and decrease the size of prefix in each step. For each new prefix calculate the XOR of elements in that prefix and add the XOR of the newly available suffix (which does not coincide with the new prefix) to the trie, then query the trie for the best possible match for the XOR of the new prefix. (Try to get 1 as the first digit if possible, otherwise put 0, then do the same thing for the second digit and so on). Get a maximum over all answers you've found, and it's all done. [By digit, I mean binary digit]

GNU C++: 3314616, 3314619

We hope you enjoyed the tasks.

Полный текст и комментарии »

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

Автор A.K.Goharshady, 12 лет назад, По-английски

I think virtual contest must end as soon as all problems are solved.

It's quite unfit for it to continue while the user can do nothing more.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +19
  • Проголосовать: не нравится

Автор A.K.Goharshady, 13 лет назад, По-английски
I wrote this post to help my friend , Iman Movahhedi , complete this one.
Round #40 was my first contest here in Codeforces and I feel I fell in love with CF just after that.

A-Translation: (C# code)
Many languages have built-in reverse() function for strings. we can reverse one of the strings and check if it's equal to the other one , or we can check it manually. I prefer the second.

Полный текст и комментарии »

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

Автор A.K.Goharshady, 13 лет назад, По-английски

Hear the song Here
این ترانه را از اینجا بشنوید

Полный текст и комментарии »

  • Проголосовать: нравится
  • -11
  • Проголосовать: не нравится

Автор A.K.Goharshady, 13 лет назад, перевод, По-русски

Итак, языком этого раунда является Io. Io (первая буква — заглавная i) — скриптовый, чисто объектно-ориентированный язык программирования с динамической типизацией. Язык был разработан Стивом Декортом (Steve Dekorte) в 2002 году. Реализация является кросплатформенной, открытой (лицензия BSD) и рассчитана на лёгкость встраивания в качестве скриптового языка (из Wikipedia). Версия, установленная на Codeforces — Io-2008-01-07 (Win32).

Одна из основных особенностей языка — минималистичность синтаксиса. Код знаменитой программы "Hello World!" на этом языке выглядит так:

"Hello World!" println

А вот пример решения задачи "A+B" (числа заданы на разных строках):

a := File standardInput readLine asNumber
b := File standardInput readLine asNumber
c := a+b
c println

Вы можете скачать интерпретатор отсюда и следовать инструкциям из дистрибутива для установки. Также дистрибутив доступен по ссылке. Пароль — f0ca4da70e5c5f80

Дополнительную информацию можно прочесть в Wikipedia, а документация доступна на официальном сайте здесь. Вы можете найти больше еще информации, используя Google. Удачи и веселого вам контеста!

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

Обратите внимание, что так как интерпретатор Io всегда возвращает код возврата 0 и не имеет возможности проверить синтаксис программы до запуска, то вердикты "Ошибка компиляции" и "Ошибка времени исполнения" будут отображаться как "Неправильный ответ".

Задачи не отсортированы от простой к сложной.


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

[Вольный перевод оригинального поста]

Всем привет!

Unknown language round #1 был проведен 21-го февраля и мы решили повторить этот эксперимент.

Он будет проведен по правилам обычного ACM-ICPC контеста. Единственная особенность раунда - задачи на нем можно будет сдавать, используя один-единственный язык программирования. Какой именно это будет язык? Пока - секрет! Мы надеемся, что вам придется его изучить во время контеста, а сам язык будет анонсирован примерно за одну минуту до начала соревнования.

Участие в этом раунде не повлияет на рейтинг - это такой веселый эксперимент. Задачи будут в большей степени ориентированы на умение писать код, чем на применение каких-либо алгоритмов.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +52
  • Проголосовать: не нравится

Автор A.K.Goharshady, 13 лет назад, По-английски
  • Проголосовать: нравится
  • +5
  • Проголосовать: не нравится

Автор A.K.Goharshady, 13 лет назад, По-английски
This post is written to help my friend , Iman , complete this one.
Problem A: Triangle (code)
For each of the possible combinations of three sticks , we can make a triangle if sum of the lengths of the smaller two is greater than the length of the third and we can make a segment in case of equality.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

Автор A.K.Goharshady, 13 лет назад, По-английски
  • Проголосовать: нравится
  • +4
  • Проголосовать: не нравится

Автор A.K.Goharshady, 13 лет назад, По-английски
This one can be solved in O(nlgn) using a segment tree.
First we convert all powers to numbers in range 0..n-1 to avoid working with segments as large as 109 in our segment tree. Then for each of the men we should find number of men who are placed before him and have more power let's call this gr[j]. When ever we reach a man with power x we add the segment [0,x-1] to our segment tree , so finding gr[j] can be done by querying power of j in our segment tree when it's updated by all j-1 preceding men.
Now let's call number of men who are standing after j but are weaker than j as le[j]. These values can be found using the same method with a segment-tree or in O(n) time using direct arithmetic:
le[j]=(power of j -1)-(i-1-gr[j])
note that powers are in range 0..n-1 now.
Now we can count all triplets i,j,k which have j as their second index. This is le[j]*gr[j]
so the final answer is 

( \sum_{j=0}^{n-1} le[j]\times gr[j] )

Полный текст и комментарии »

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

Автор A.K.Goharshady, 13 лет назад, По-английски
This one has two different linear-time solutions. Greedy and dynamic programming.

Greedy solution:
You should stop at the city with maximum distance from the root (city number 1). So all roads are traversed twice except for the roads between the root and this city.

Dynamic Programming:
For each city i we declare patrol[i] as the traverse needed for seeing i and all of it's children without having to come back to i (Children of a city are those cities adjacent to it which are farther from the root) and revpatrol[i] as the traverse needed to see all children of i and coming back to it. we can see that revpatrol[i] is sum of revpatrols of its children + sum of lengths of roads going from i to its children. patrol[i] can be found by replacing each of revpatrols with patrol and choosing their minimum.


Полный текст и комментарии »

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

Автор A.K.Goharshady, 13 лет назад, По-английски
The code for converting decimal numbers to Roman was on Wikipedia , so I'm not going to explain it.
Since we have the upper limit 1015 for all of our numbers , we can first convert them to decimal (and store the answer in a 64-bit integer) and then to the target base.
For converting a number to decimal we first set the decimal variable to 0, then at each step we multiply it by the base and add the left-most digit's equivalent in base 10.
We had some tricky test cases for this one which got many people :
test #51:
2 10
0
many codes printed nothing for this one, this was also the most used hack for this problem

test #54:
12 2
000..00A
a sample of having initial zeros in input

test #55:
17 17
0000000...000
There were many people who just printed the input if bases were equal

there were two nice extremal hacks:
2 R
101110111000 
and
10 2
1000000000000000

Полный текст и комментарии »

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

Автор A.K.Goharshady, 13 лет назад, По-английски
In this problem signs can be ignored in both initial and answer strings, so first we remove signs from initial strings. Then we make a list of the six possible concatenations of the 3 initial strings and convert all of them to lowercase.
For checking an answer string , we remove the signs , convert it to lowercase and check if it is just one of those 6 concatenations.

There were two really nice hack protocols , the first one is:
-------__________;
_____;
;;;;---------_
2
ab____
_______;;;

Here all concatenations become empty.

The second one was putting 0 as number of students :D

Полный текст и комментарии »

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

Автор A.K.Goharshady, 13 лет назад, По-английски
Problem A:
This was indeed the easiest problem. You just needed to XOR the given sequences.
The only common mistake was removing initial 0s which led to "Wrong Answer"
Common mistake in hacks which led to "Invalid Input" was forgetting that all lines in input ends with EOLN.


Полный текст и комментарии »

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

Автор A.K.Goharshady, 13 лет назад, По-английски
سلام
بسیار مفتخرم که شما را به شرکت در پنجاه و هفتمین کانتست دعوت کنم.
طراحان این کانتست علیرضا فرهادی و من هستیم

همچنین از زحمات مایک میرزایانف - آرتم راخف - سعید ایلچی - محمدجواد نادری - جرالد آگاپف  و ماریا بلوا نهایت تشکر را داریم

به مناسبت روز ملی مهندس این کانتست را به خواجه نصیرالدین توسی تقدیم می کنیم


در این کانتست برای اولین بار صورت سوالها به زبان پارسی هم منتشر می شود.
می توانید صورت سوالها را پس از شروع کانتست از اینجا ببینید

کانتست به پایان رسید
:برنده

Полный текст и комментарии »

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

Автор A.K.Goharshady, 13 лет назад, перевод, По-русски
Этот перевод был сделать "Google", я не уверен, что это правильно: D

Это полу-Учебник для codeforces # 42 (Div.2), я не собираюсь объяснять все, но я просто говорю идей.
Проблемы были чрезвычайно приятно.

А) это довольно очевидно, вы можете хранить две строки и сколько раз каждый из них произошли
Б) для каждого из верхнего или нижнего регистра, заботиться о том, сколько раз она появилась в каждой из строк. , если для символа х, х повторений во второй строке более чем первой строки, мы не можем это сделать, в противном случае ответа "да".
C) Все мы знаем, что оставшаяся часть числа при делении на 3 равно оставшуюся сумму своих цифр при делении на три. Так что мы можем поставить все входные числа в 3 подхода на основе их остаток на 3. Те, у кого остаток 1 могут быть сопоставлены с теми, с остатком 2, а также с остатком 0 может быть согласован с самим собой. Так что ответ:
половина из числа тех, делится на три минимум имеющие остаток 1 и тех, кто оставшуюся часть 2
D) На самом деле мы ищем Эйлера тура. Я нашел это так:
Если хотя бы одно из т и п даже сделать это, как эта цифра:

другой сделает это, как это и добавить телепортироваться с последнего квадратного к первому:


Но было очень приятно хаки, как я изучил их. как эти два:
1 10
и
1 2

E) Давайте просто заботиться о 2 машины и посмотреть, сколько раз они изменят свою позицию. Это легко. Так сделайте это для всех автомобилей: D

Полный текст и комментарии »

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