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

Автор Golovanov399, 3 года назад, По-английски

Hello, codeforces!

I have created a tool for testing interactive problems. If you do not know what it is, I recommend you to read Interactive Problems Guide before/instead of reading this blog. It is important to understand that this tool does not help, in any way, to solve interactive (and all other types of) problems, where by "solve" I mean "come up with the solution". Today's June Lunchtime introduced an interactive problem called XOR, The Detective, where I used my tool and it helped me to debug my solution, so I would like to use this chance to show the tool in work. With all of this out of the way, let's begin.

Debugging interactive solutions in general

I can't say about everyone, but for me personally debugging a solution to an interactive problem is much harder than to a non-interactive one. First of all, basic testing on samples is already non-trivial: while usually I copy-paste the sample into a file, which I then read from, it does not work this way with interactive problems. I don't know which queries my solution is going to ask, and hence what to respond; so I can't write all the answers into the file, as I don't know them in advance. And even if I have tested the solution by manually entering the correct responses, and then I want to test it on the same test again (say, I fixed a minor bug), I cannot simply select all text and paste it into the input file, because I need to separate the queries from the responses.

Moreover, calculating the responses itself requires visualizing things in my head or calculating xors or something, which takes time and efforts.

So what one usually does to (stress-)test an interactive problem is the following: comment the parts of the code which read stuff and replace them by internally calculating the answer with some chosen input. For example, instead of:

int ask(int x) {
    cout << "? " << x << endl;
    int res;
    cin >> res;
    return res;
}

one can use something like:

int ask(int x) {
//  cout << "? " << x << endl;
//  int res;
//  cin >> res;
//  return res;
    return calculate_answer(x);
}

If one doesn't want to comment/uncomment stuff before each submission, they can use macros, for example:

int ask(int x) {
#ifdef TEST
    return calculate_answer(x);
#else
    cout << "? " << x << endl;
    int res;
    cin >> res;
    return res;
#endif
}

Then the only change that needs to be done before submission is commenting the line with #define TEST (or even nothing, if you compile your code with -DTEST).

Personally I like this way, because it is quite fast, convenient, and automatically allows you to use internal implemented stuff when answering a query (for example, if your solution calculates the depth of every vertex in a rooted tree anyway, you can use it to return the distance between two vertices).

So what does this tool do?

The tool works in the following way: you write an interactor and then run something like interact ./solution ./interactor, where solution and interactor are your executables. Some advantages in comparison with the first method:

  • You don't need to change your code before submission;
  • Usually it is easier and faster to write the interactor from scratch (arguable, but it is certainly almost never longer or more difficult);
  • You see the colored interaction protocol, where it is also easy to see which line was printed by which program.

For example, in the problem I mentioned, when I finished implementing my solution, to test it, I wrote the following simple interactor:

int.cpp

When I ran interact ./qwe ./int, I saw this:

output of the command

Because of this report, I found that my code didn't manage to properly restore the bits where two numbers differ, so I knew which part of my code was faulty. And indeed, after fixing a bug I got this:

interact ./qwe ./int

After I submitted my code, it passed all the tests.

Installation and usage

The script can be downloaded from my github. To use it, one simply runs python3 interact.py <args>. It is probably more convenient to setup the following workflow, though:

  • Create a directory for such scripts (optional);
  • Move the script in such a directory (or in any other);
  • If you use Linux, you may make this file executable using chmod +x interact.py;
  • If you use Linux + Terminal, add the following line in your .bashrc or .zshrc: alias interact="python3 <path-to-script> --color". In my case, it is alias interact="$HOME/misc/interact.py --color" (I omit python3 because I made the script executable). To use it immediately after this, you may need to relaunch the terminal or run source ~/.bashrc (source ~/.zshrc and similar);
  • If you use Windows, you may want to add the directory containing this script in the path variable. Probably, you also need something to make the script executable, I don't know anything about this.

After these steps you should be able to run the script from anywhere using the interact command. How to use it, though?

If you run interact -h you will see the following message:

interact -h

I think it is self-explanatory. One note: you need the solution and interactor executables to be single-file commands. For example, if you write the solution in python and run it with python3 sol.py, you can't specify this two words command as <solution exec>. It is easy to fix, though; maybe I'll do it.

I haven't tested it much, so feel free to report bugs or something. I also want to emphasize that this tool doesn't do anything useful except neat visualization of the interacting process; and is probably not going to be in need of frequently. Also, as far as I remember, this script should not require any additional libraries, but if it does, just install what it requires.

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

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

Автор Golovanov399, история, 3 года назад, По-английски

Happy new year everyone!

The next projecteuler problem is in 30 minutes. If you want to receive such notifications half an hour before other pe problems, feel free to subscribe to https://t.me/pe_in_30, its sole purpose is exactly this. It should work most of the time.

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

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

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

Приносим извинения за некоторые проблемы в задачах

Problem A of tc/div2 (В поисках Саске)
Problem B of tc/div2 (Новая техника)
Problem C of tc/C div2/A div1 (Простота исполнения)
Problem D of tc/D div2/B div1 (Сюрикены)
Problem E of tc/E div2/C div1 (Oracle соло мид)
Problem F of tc/D div1 (Дороги и рамен)
Problem E of div1 (Выпуклая игра)

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

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

Автор Golovanov399, 4 года назад, По-русски

Добрый день!

В воскресенье, 25-го сентября в 14:05 по московскому времени состоится Отборочный Раунд 1 олимпиады для школьников Технокубок 2021. Раунд будет длиться два часа, участникам будут предложены 6 задач. По его результатам лучшие участники (но не более 45% от общего числа участников раунда) будут приглашены на финальный этап в Москву. Для регистрации на раунд и участия перейдите по ссылке. Не забудьте заранее зарегистрироваться на раунд! Для опоздавших будет открыта дополнительная регистрация (с 14:15 до 16:05).

Зарегистрироваться на Отборочный Раунд 1 →
Соревнование открыто для всех в виде отдельных раундов для первого и второго дивизионов.
Для всех участников всех трех редакций этого соревнования будет пересчитан рейтинг.

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

Напомним, что согласно правилам раундов Codeforces во время соревнования ваши решения будут тестироваться только на претестах (предварительном и неполном наборе тестов), а системное тестирование состоится после окончания раунда. Обратите внимание, что претесты не покрывают все возможные случаи входных данных, поэтому тщательно тестируйте свои программы! После прохождения претестов у вас будет возможность заблокировать решение, тем самым получив привилегию искать ошибки и взламывать чужие решения, но отказавшись от возможности перепослать ваше решение при каких-либо обстоятельствах (например, даже если вы найдете ошибку или вас взломают). Со временем задачи падают в стоимости. После системного тестирования учитываются только полные решения. Подробнее про правила соревнований можно прочитать по ссылкам:

Регистрация на олимпиаду Технокубок еще открыта. Победителей и призеров олимпиады ждут значительные квоты при поступлении в престижные технические вузы России и ценные призы! Если Вы школьник 8-11 классов и пока не зарегистрировались на Технокубок, то самое время сделать это:

Зарегистрироваться на олимпиаду →
После регистрации на олимпиаду не забудьте зарегистрироваться на Отборочный Раунд!

В финал соревнования будут приглашены лучшие участники каждого из отборочных раундов (но не более 45% от общего числа участников раунда).

Авторы отборочного раунда — AndreySergunin, Endagorion, amethyst0 и я, Golovanov399. Спасибо KAN и 300iq за координацию. Кроме того, хочу выразить благодарность тестерам, без помощи которых этот раунд не состоялся бы: kalki411, 300iq, arjunsanjeev7, brunomont, Chocobar, iankury, low_, psevdoinsaf, JinhaiChen и teapotd!

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

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

Автор Golovanov399, 4 года назад, По-английски

Hello everyone,

Mike said that they will likely make the streams tab hideable, but it probably takes time. On the other side, implementing a simple userscript took me 5 minutes, so here it is:

userscript

To install a userscript, you can use the Tampermonkey extension, or if it is not secure or does not work with your browser, google what you should use for yourself. Anyway it is probably a temporary option. There is also another way provided by dpaleka.

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

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

Автор Golovanov399, 5 лет назад, По-английски

Hello, codeforces.

I would like to tell you about some tricks and constructions I use in C++. They are not hidden or anything, moreover, most of them are from stl or maybe well known among software engineers, but I often see codes where something is done by hand in, say, 5 lines, while in stl there is a function which does the same.

The things below are filtered by my personal sense of non-popularity (so no __builtin functions) and usage frequency (so there almost surely are similar things I don't know about) and are not really sorted in any reasonable order. Let's begin.

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

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

Автор Golovanov399, история, 5 лет назад, По-английски

We hope that no difficulties, misunderstanding and "wtf am i asked to do" thoughts ruined your fun!

Problem A: Nash equilibrium
Problem B: DAG
Problem C: Segment tree or Fenwick?
Problem D: Dijkstra
Problem E: Amazing bitset

In problems F, G and J we don't mention in the editorial that we assume you to have parsed the statement into a convenient programming-friendly format.

Problem F: Keep talking and nobody explodes -- easy
Problem G: Keep talking and nobody explodes -- medium
Problem H: Who needs suffix structures?
Problem I: Deja vu
Problem J: Keep talking and nobody explodes -- hard

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

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

Автор Golovanov399, 5 лет назад, По-английски

Hello everyone!

I'm travelling abroad Russia. It happens that I see things which I haven't seen before (obviously), and it isn't necessary about culture (not so straightforward). For instance, recently I saw a payphone with internet access:

proofpics

I don't know if it's a casual thing in some countries, but I haven't seen not only things like this in my life, but also any working payphone for last ~18 years.

So I wondered if it's possible to submit a problem on codeforces using it. Surprisingly, the payphone was quite convenient, one just needs to get used to it :)

So I challenge everyone to get AC on any problem from the cf problemset using any non-trivial device like smart tv idk or a fridge or whatever your imagination tells you to use. Good luck and have fun!

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

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

Автор Golovanov399, 5 лет назад, По-английски

Hello everyone.

A flashmt's comment (thank you) gave me an idea to modify a css on all code jam pages so that it doesn't suck that much. So what we need is:

How to use it:

  1. In stylish select somewhere "create new style",

  2. Press the "write new style" button,

  3. Copy this css contents to the code section,

  4. Tell this to apply to all urls starting with https://codingcompetitions.withgoogle.com,

  5. Click the save button.

What it does so far:

  • removes the problem graphs section,

  • removes the "show round overview" toggle,

  • reduces the height of all buttons,

  • makes the section with problems scrollable.

I didn't manage to find out how to make the width of problems columns less so that everyone could see when a round contains 4 problems, not 3. Feel free to comment how to do it if you know (or suggest some other modifications).

And some gifs related.

Before After

I hope that I didn't break something (like accidentally hide the questions button or something), but I'm not sure, so use it at your own risk. I've tested it only in firefox, but it should seem that this must work everywhere (like come on, it's just a css modification).

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

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

Автор Golovanov399, история, 5 лет назад, По-английски

Hello everyone.

Recent codechef long challenge had a task about queries on paths inside a tree: short, given a tree, each vertex contains a linear function, and given $$$q$$$ queries of types "add given linear $$$f$$$ to all vertices of the path between $$$u$$$ and $$$v$$$" and "calculate maximum of $$$f(z)$$$ where $$$z$$$ is given and $$$f$$$ is a function in any of vertices on the path between given $$$u$$$ and $$$v$$$", $$$n$$$ and $$$q$$$ are $$$\leq 10^5$$$, time limit is 4s.

It seems that the intended time complexity is $$$O(n\sqrt{n}\log{n})$$$, but I heard that it required efforts to get AC with this solution. On the other hand, it's easy to get ac with an $$$O(nq)$$$ solution.

Don't get it wrong: if we iterate over a path just, for example, by going from both endpoints towards the root, it gets tl (even with pragmas): submission. On the other hand, one can use heavy-light decomposition (this particular implementation is not necessary, I suppose, but it's still very nice) first (that is, sort every vertex' children by their subtree sizes), then rearrange vertices by their dfs in-order, and voilà, every path is now a union of about $$$\sim\log{n}$$$ consecutive segments. If we now do basically the same stupid implementation of what we are asked for in the statement, we get ac for 1.6s with pragmas and even ac for 2.6s without pragmas.

Hope this trick is not a mutual knowledge (though it's definitely not a common knowledge). I found it so simple and potentially usable that it deserves a post in my opinion.

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

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

Автор Golovanov399, история, 6 лет назад, По-английски

Hi everyone.

Some time ago I've written a script which notifies user about fresh changes in the standings during an atcoder contest (under some reasons, one but not the only of them being the last agc, I recalled it just today). More precisely, you set the contest name and a constant $$$k$$$ (5 by default), and you get a notification for each of the first $$$k$$$ accepted submissions on each problem in the contest. This is how it looks in my laptop (I've run it after the contest finished, so that's why there are a lot of notifications):

Some details:

  • The script can be downloaded here. Run python qwe.py -h for help.

  • I use notify-send to notify, so one must have this utility to run this script. This can be replaced by your own way, though (change the line 43 in qwe.py).

  • I cannot surely determine the task letter by its code (maybe it can be uniquely determined by the last digit, but I am not sure), but I assume that in each contest problems have consecutive codes and the problem A is likely to be solved first.

  • In problems with partial scoring any positive score is considered. Moreover, if one passes the problem on, say, 800/1300, and then completely solves it on 1300/1300, you get a notification only for the first submission with positive score for this user.

  • It may distract, so use at your own risk.

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

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

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

Ещё раз приносим извинения за то, что не проконтролировали ситуацию с ранним разбором, а также за сообщение о неэтичном поведении участников: вот комментарий к этому сообщению. При попытке сдвинуть задачу про казино на позицию ниже что-то пошло не так, и она сдвинулась на позицию выше (несмотря на это, Radewoosh не ощутил, поздравляем!).

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

Задача A финала/див2 (Технокубок Огня)
Задача B див2 (Майк и дети)
Задача B финала/C див2 (Системное тестирование)
Задача C финала/D див2/A див1 (Диана и Лиана)
Задача D финала/F див2/C див1 (Сжать строку)
Задача E финала/E див2/B див1 (Случай в казино)
Задача F финала/D див1 (Дерево власти)
Задача G финала/E див1 (Тот самый Мюнхгаузен)
Задача H финала/F див1 (Секретные письма)

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

Разбор задач Технокубок 2019 - Финал
  • Проголосовать: нравится
  • +157
  • Проголосовать: не нравится

Автор Golovanov399, 6 лет назад, перевод, По-русски

Всем привет!

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

Поэтому я решил написать скрипт, который будет показывать правильные цвета и звания. Я считаю, это не убивает идею маскарада (во всяком случае, не до конца): всякий, кто хочет поучаствовать в этом, может проигнорировать этот пост и по-прежнему видеть, какие цвета себе поставили другие пользователи (включая их самих). С их точки зрения ничего не меняется.

Из-за этого расширения страница будет грузиться чуть дольше, потому что придётся загрузить файл размером примерно ~1.6мб. Расширение не меняет звание на странице конкретного человека (мне было лень), но всякие цвета людей в блогах, комментариях, прямом эфире и так далее должны стать нормальными. Расширение также не трогает заставку со снежинками, потому что убивать новогоднее настроение -- это не то, чего я хочу.

UPD: я обновил расширение, теперь оно кеширует нужный файлик и не качает (теперь уже) 4 мегабайта при каждой загрузке страницы.

Всем счастливого нового года!

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

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

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

Нам очень жаль, что вы испытывали проблемы с доступом к Codeforces.

Задача A отбора/див2
Задача B отбора/див2
Задача C отбора/див2
Задача D отбора/див2 = задача A див1
Задача E отбора/див2 = задача B див1
Задача F отбора/див2 = задача C див1
Задача G отбора/див2 = задача D див1
Задача E див1

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

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

Автор Golovanov399, история, 6 лет назад, перевод, По-русски
Tutorial is loading...
Tutorial is loading...
Tutorial is loading...
Tutorial is loading...
Tutorial is loading...
Tutorial is loading...
Tutorial is loading...

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

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

Автор Golovanov399, 7 лет назад, По-английски

Hello everyone,

About 7 months ago I posted here about a tool for converting some rectangular grid cell coordinates into a sort of interactive picture. riadwaw proposed to make the same for hexagonal grids. Personally for me drawing hexagons during the contest is a pleasure, but it takes time and it's definitely a good idea to make such tool. Yesterday I remembered about this and made it, so welcome. Here are some use cases.

When you proceed, you should see something like this:

This tool does almost the same as the rectangular one, but there are some differences:

  • Show axis directions checkbox. The most useless checkbox, it just shows you the axis for the used coordinate system without even labeling them.

  • Show coordinates checkbox. Writes a pair of coordinates in each cell.

  • Show cell under cursor. If in the previous version cursor revealed coordinates of the cell which it was over, here it highlights this cell. However, it has some limits, read further.

  • Show grid. Shows cell borders. Here is where the evilest evil hides. You see, drawing a rectangular grid of size n × m requires drawing O(n + m) lines. Here is a different story. To draw a hexagonal grid of size about n × m one should draw O(nm) segments. Of course they can be decomposed into O(n + m) (intersected) paths, but I'm not sure whether it will reduce the drawing time (however, it'll reduce the number of .beginPath() commands, but I don't know if it's so slow in js). This is why there is a size threshold after which grid drawing may take a long, and one can unmark this checkbox to draw only needed cells (of course in O(theircount)). It's especially annoying if one moves his mouse over a big grid which is being redrawn after each move (yes, maybe after a while I will not erase everything but repaint only the cell under cursor), so if the bounding box is big enough, one can see an icon with a cursor and a cell crossed out. This means that the cell under your cursor will not be highlighted independently of the previous checkbox. It's made in order to make this ugly performance less visible for users.

Maybe (not very likely) some new functionality will be added. You can copy and modify any code you'll find.

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

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

Автор Golovanov399, история, 7 лет назад, По-английски

Hello everyone,

Some of you may know about recently discovered vulnerabilities (well, technically, there in one vulnerability and two attacks using it). I am not a cybersecurity expert, I know what is going on about the "read-all-those-breaking-news-titles" level, but as I understood, some things can slow down by 30%. So I have a couple of questions:

  1. Do testing systems like codeforces, yandex.contest, topcoder, atcoder, csacademy etc apply the patch? I don't know if testing machines store something that is important and shouldn't be stolen.

  2. If yes, does this mean that we now should multiply all time limits by 0.7? Maybe this coefficient is not so small because 30% is reached on some other type of operations which are not used in cp? On the other hand, branch prediction is used almost always in cp, as I know.

Somebody who knows how this works, answer, please.

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

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

Автор Golovanov399, 7 лет назад, По-английски

Hello, everyone.

I guess that those of you who doesn't solve problems only in his mind use pen and paper to make some notes, eg draw graphs, points, lines, permutations, shortly, everything. It's very convenient, but there are tools on the internet that make this process more comfortable in several cases: for example, a graph editor or a geometry widget (there was a nice page by zxqfl, but it seems to be expired or something). All these services allow to obtain visualizations from some (debug-)print-friendly format, which can save your time.

Once I decided to write a tool for drawing grids (as I remember, it was approximately when I was solving the task from the last russiancodecup). You can find it here. Some usecases are also provided. The default text in the textfield is a brief manual, but you can type something and see what happens.

Below you can see an example of usage (based on the problem from rcc above):

Maybe (not very likely) some new functionality will be added. You can copy and modify any code you'll find.

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

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