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

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

Recently one my friend got a TL verdict in some problem, and another my friend tried to help him to overcome it. Then I joined, got shocked by the results they got and we together stabilized the approach they came to.

By "deep recursion" we will mean a recursion with depth >= 100000. If it's less than 1000, this approach doesn't work at all, if it's between 1000 and 100000, most likely the speedup won't be so high so that will be decisive.

Let's consider this simple DFS function (it just counts the number of vertices):

private int dfs(int x, int p, List<Integer>[] g) {
    int result = 1;
    for (int y : g[x]) {
        if (y == p) {
            continue;
        }
        result += dfs(y, x, g);
    }
    return result;
}

generate a chain tree with 500000 vertices:

int n = 500000;
List<Integer>[] g = new List[n];
for (int i = 0; i < n; i++) {
    g[i] = new ArrayList<>();
}
for (int i = 1; i < n; i++) {
    int p = i - 1;
    g[i].add(p);
    g[p].add(i);
}

and run it:

long t1 = System.nanoTime();
int result = dfs(0, -1, g);
long t2 = System.nanoTime();
System.out.println("time = " + (t2 - t1) / 1.0e9 + " sec, result = " + result);

On my computer it runs 1.8 sec. Too slow for such a simple function, isn't it?

Let's speedup it. First, add two dummy parameters curDepth and maxDepth to DFS:

private int dfs(int x, int p, List<Integer>[] g, int curDepth, int maxDepth) {
    if (curDepth > maxDepth) {
        return 0;
    }
    int result = 1;
    for (int y : g[x]) {
        if (y == p) {
            continue;
        }
        result += dfs(y, x, g, curDepth + 1, maxDepth);
    }
    return result;
}

and then... OMG WTF

long t1 = System.nanoTime();
for (int i = 0; i < 100000; i++) {
    dfs(0, -1, g, 0, 0); // JIT please
}
int result = dfs(0, -1, g, 0, Integer.MAX_VALUE);
long t2 = System.nanoTime();
System.out.println("time = " + (t2 - t1) / 1.0e9 + " sec, result = " + result);

Now it works for 0.1 sec :)

When some method in Java is called too frequently, JIT optimizes it. It gets recompiled in runtime and on every new call the recompiled version will be called. However, the method cannot be recompiled while it is being executed. See this StackOverflow thread for more info. Maybe some Java expert can add something?

So in the first example, we enter into not optimized version of DFS and use it all the time. In the second example we do a lot of very short DFS calls, it for sure gets optimized, and finally we use optimized version to solve the actual problem.

Make sure the warming up does many calls but doesn't do many operations. In this example it's wise to do these fake DFS calls from a leaf and stop after the first recursive call.

Make sure all branches in your recursive function are actually run. It would be wrong to call dfs(0, -1, g, 0, -1) because the execution finishes quickly on if (curDepth > maxDepth), and the remaining code with iteration over adjacency list is not run and therefore is not optimized.

It doesn't work very well on Codeforces:

But it works just fine on Ideone:

and also works on:

  • Atcoder
  • CSES
  • Yandex.Contest in Java 8 compiler
  • ...

Maybe it's Windows/Linux or 32-bit/64-bit or OpenJDK/Oracle JDK differences, I haven't tested it yet.

Once more, it works only when recursion has depth >= 100000, and only on specific sites. But maybe it will help someone, and it is funny anyway.

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

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

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

Problem or Question?

Question is a short phrase, requiring a short answer. Examples of questions:

  • What's your name?
  • Where are you from?
  • What drinks do you prefer?

Some say interview questions are problems, but that's not correct, most of the interview questions are either short and require short answer...

  • How to compile a C++ source file?
  • What is the complexity of mergesort?
  • How add a file to a Docker image?

... or the interviewer may want to hear how you design a system with microservices and so on, which is can't be called a problem too.

Problem is something complicated but strict. You need to solve a problem a get a solution.

Problems exist not only in competitive programming, but also in math or physics competitions, in chess.

Examples of problems:

Why does one particular nation misuse the word "question"?

  • Their native language seems to have the same word for these concepts, and they don't care English does have different words.
  • Many of them get into competitive programming because of jobs, they got used to this "interview question" phrase, and as in their country technical interview is closely connected with competitive programming problems, they replace problems with questions.

What to do with contests?

I think the default word is to take part or to participate. My language allows the words play or write, they both make sense because contest is like a game, you compete (another good word) against other players, and you write code on contests.

The word give is wrong. When you say "give", you mean you no longer have something, and someone else receives this something from you. How are contests connected with it? No data.

People from the known country say they use the word "give" as they use it in the phrase "give an exam", which is wrong too and is surely related to their native language. You can pass or fail an exam or you can take an exam (note that "take" is literally the opposite word for "give")

Conclusion

I'm not a native speaker. But when someone says I'm wrong at something, I try to remember it and not to repeat the same mistake in the future. The most numerous nation on Codeforces don't. It is disrespectful.

Please don't use Indian English. It is ugly and contradictory.

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

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

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

Hello everyone,

As you may know, ICPC movement has officially died in my university. It was a streak of 14 NEERCs in a row, with 3 WFs, but now it's over and it doesn't seem to recover in near future. Let's celebrate this event with Samara Farewell Contest, and don't forget to press F!

It is a collection of not-so-easy (still easy for nutellas) problems authored by dalex and craus throughout our ICPC career and then problemsetting career. Find the enter links on Opencup site on Sunday, January 3, 2021, 11:00 MSK.

We can discuss the problems here after the contest ends. I will also upload it to Codeforces Gyms, but a bit later.

Links:

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

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

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

Всем привет.

В этом году в рамках нашей олимпиады в Самаре (ссылка) также состоялось и экспериментальное соревнование с марафонской задачей. Такие задачи вы могли встречать на Marathon 24, Deadline 24, Google Hash Code, и вот совсем недавно прошел ICPC Challenge. Оказывается, Codeforces поддерживает и такие задачи тоже, и этот пост послужит инструкцией, как же такие задачи делать. Раз уж MikeMirzayanov нигде об этом не написал, это сделаю я.

Ссылка на контест: 2020, XIII Самарская областная межвузовская олимпиада по программированию (марафонская задача)
Длительность в оригинальном соревновании была 4 часа, так что можете порешать виртуально и сравнить с результатами онсайта:

Лучшие результаты онсайта

Итак, как же делать такие задачи и такие соревнования? Оказывается, все очень просто. Отличия от обычных задач следующие:

  • в задаче должен быть всего один тест, который надо предварительно куда-нибудь загрузить (например, на gist.github.com), а потом дать участникам ссылку для скачивания.
  • в чекере нужно использовать функцию void quitp(double points, const std::string &message = "") или template<typename F> void quitp(F points, const char *format, ...).
  • в чекере нельзя выводить ничего в stderr (если быть точным, нельзя слишком много выводить в stderr), это почему-то ломает его и он начинает всегда возвращать 0 баллов. У меня нет идей, почему это происходит, но что есть то есть.
  • в настройках контеста нужно поменять тип контеста на IOI (по умолчанию он ICPC).
  • в настройках контеста нельзя выставить язык Text, зато существует волшебный язык PHP, который для таких задач работает аналогично Text и просто средиректит текст программы (ваш аутпут) в выходной поток. Надо только проследить, чтобы любой возможный ответ на тест не превышал source limit.

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

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

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

Привет.

29 марта в Самарском университете состоялась ежегодная олимпиада по программированию (конечно, онлайн), и мы снова выкладываем ее в тренировки Codeforces. Тренировка пройдет в воскресенье, 5 апреля, в 11:00 MSK.

Ссылка на контест
Ссылка на виртуальное участие

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

Список наших предыдущих контестов
Список наших очень старых контестов (возможно, менее интересные, более простые, не переведены на английский)

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

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

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

Please put to main page. So we won't see blogs like https://codeforces.com/blog/entry/70236 in the nearest future.

In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.
In C++, comparator should return false if its arguments are equal.

Hope you remember it and will never make such a stupid mistake!

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

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

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

Некоторое время назад я подумал, почему бы не загрузить наши древние контесты в тренировки. Некоторые из них можно найти на сайте http://contest.uni-smr.ac.ru/ — их я трогать не стал — можно и там решать. Некоторые контесты оказались безвозвратно утеряны. Но вот три штуки удалось откопать на жестком диске Shlakoblock-а.

Shlakoblock является автором всех трех, во втором из них я, тогда еще сине-зеленый, ему помогал. Первый контест личный, второй и третий командные. Держите:

За качество, разумеется, не отвечаю. Как и в любых контестах сине-зеленых авторов, тут будут встречаться и некачественные условия (факт, хотя я немного их подфиксил), и слабые тесты (не факт, но я почти уверен), и бояны из учебника (еще какой факт, но для того времени было норм). Тем не менее, несколько прикольных задач там есть. А еще ввод-вывод файловый: input.txt/output.txt — мы тогда не умели настраивать тестирующую систему под stdin/stdout.

Уровень я поставил три звезды, но может, было более правильно поставить две. Все-таки это 2010-2011 годы, тогда никто еще ничего не умел. Можно заценить, насколько с того времени вырос уровень олимпиадников. По моей оценке, современные фиолетовые должны решать все.

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

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

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

Всем привет.

Можете ли вы представить, что монитор (тот, который положение участников контеста, а не который надо разбивать после этого контеста) может быть вреден? На самом деле такое встречается нечасто, но в этом посте мы разберем два таких примера, а также попробуем предложить возможное решение этой проблемы. По идее, для MikeMirzayanov не должно быть проблемой реализовать эту фичу.

Итак, первый пример, 2015 год, четвертьфинал Южного региона в Саратове. Пруфы тут будут такие себе, так как контест куда-то исчез с CF. Вот тут этот контест был, когда я его писал: https://codeforces.com/contest/589 (можете глянуть 14-ую страницу моих посылок, там еще задачи были пошаффлены), вот анонс: https://codeforces.com/blog/entry/20989, а сейчас ссылки на задачи ведут в тренировку с id 102042, закрытую от всех. Непорядок! Тем не менее, постараюсь рассказать, что там было.

Официальные стендинги: http://neerc.ifmo.ru/archive/2015/southern/standings.html Мы видим на первом месте с 11 задачами команду Нижнего Новгорода, на голову сильнее остальных (так оно и было на самом деле). Но давайте себя поставим на место одной из команд, решивших 7 задач. Вопрос: на часах 3:00, два часа до конца. Какую задачу решать восьмой по счету?

Мы видим, что все команды, пытавшиеся сдать 8-ую задачу, пробовали сдать задачу I. Именно задачу I сдала восьмой по счету команда Нижнего Новгорода. Между тем, когда этот контест проводился на Codeforces через пару дней после четвертьфинала, почти все команды из фиолетовых-желтых участников решили 8+ задач, а восьмой они сдали задачу, которая в официальном мониторе обозначена как G. Кроме того, команды, решившие 9 задач, примерно поровну сдавали I и K из официального монитора (к примеру, мы тогда сдали 9 задач, и девятой сдали именно K). Пруфов, как я уже написал, не будет, так как контест куда-то удалили.

Ошибка всех команд с онсайта состояла в том, что они пытались следовать за командой, в составе которой были vepifanov и KAN. Для этих ребят сложность 8-10 задач была примерно одинаковая: примерно very easy. Но для более слабых участников это вовсе не так! Им не стоило копировать порядок задач, стоило подумать своей головой, а не смотреть в монитор. И тогда бы они обнаружили и то, что G халява, и то, что K не очень то уж и сложнее I.

В случае с четвертьфиналом Южного региона 2015 правда о сложности задач хотя бы вскрылась на зеркале, но вот второй пример меня полностью поразил. Это случилось совсем недавно, когда мы выложили контест, проводившийся в этом году в Самаре: https://codeforces.com/gym/102215, анонс: https://codeforces.com/blog/entry/67178 Результаты как онсайта, как зеркала, так и того, что в нем происходило потом, в виртуальных участиях, абсолютно неадекватны. Не в том плане, что слабые обгоняют сильных, а в плане порядка решения задач. Постараюсь не особо спойлерить.

В принципе, что на онсайте, что в зеркале происходило одного и то же. Итак, начинается контест, и желтые участники начинают решать задачи по порядку. Читают первую — сдают за 10-15 минут. Читают вторую — она еще легче, сдают за 5-10 минут. Читают третью — тоже легкая, тоже сдают. Читают четвертую — ну тут конечно кода побольше, но тоже легкая, сдают уже за 20 минут. И так далее.

А между тем зеленые видят монитор и недоумевают, а чего это контест какой сложный. Почему вторая по сложности задача какая сложная, на нее полчаса нужно! А на третью еще полчаса, а на четвертую целый час! Ответ прост: не нужно следовать за теми, кто намного сильнее тебя. Для желтых почти все задачи в этом контесте легкие, желтые решают их буквально с прочтения. Как минимум три задачи, сложность которых я оцениваю как very easy, остаются почти неоткрытыми до третьего/четвертого часа, где их обнаруживают желтые после того, как они решили намного более сложные задачи. А на онсайте одну из этих very easy задач вообще first-accept-нул участник, решивший ТОЛЬКО эту задачу.

Я думаю, если написать этот контест, сначала прочитав все задачи, а потом вообще не смотря в монитор, результат будет лучше, чем если бы вы использовали монитор по назначению. И точно не будет (цитата) туплю, чтобы мне на четвёртом часу таблица предложила [решить задачу уровня Div2B]. Если вы слабо-желтый и ниже, можете попробовать, а потом взглянуть на таблицу и, мягко говоря, удивиться.

Ну а теперь feature request. Нужно добавить два параметра в монитор — верхнюю и нижнюю границу рейтинга участников, показываемых в мониторе и внизу монитора (там, где говорят, сколько человек какую задачу решило). В принципе, можно только верхнюю. Например, я бы поставил себе верхнюю границу 2300 или 2400 и мне бы это отлично подошло — мне неважно, сколько там решил условный турист, это для меня не показатель. Турист может решить за 5 минут то, что я не решу за 5 часов. Намного более важно, какие задачи решают люди, равные и чуть более сильные по скиллу (ну а более слабые точно не помешают). Сделаем результаты более адекватными!

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

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

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

Привет.

19 мая в Самарском университете состоялась ежегодная олимпиада по программированию, и мы снова выкладываем ее в тренировки Codeforces. Тренировка пройдет в субботу, 25 мая, в 10:00 MSK.

Ссылка на контест
Ссылка на виртуальное участие

Этот контест уже четвертый год проводится личным. Поэтому просим всех тоже участвовать лично. Наиболее интересно должно быть фиолетовым и синим участникам.

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

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

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

Hi,

I was allowed to upload two contests from Petrozavodsk camps, Yandex Cups 2018 and 2019, into Codeforces Gyms:

These contests are mostly authored by Zlobober and ifsmirnov, with the help of some other people. Yandex Cup 2018 has more easier problems and less hard problems.

The 2018 one is also known as Grand Prix of Khamovniki (discussion on CF), the 2019 one was never published before.

Enjoy!

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

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

Автор dalex, история, 5 лет назад, По-английски
  • Проголосовать: нравится
  • +44
  • Проголосовать: не нравится

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

Hello!
I want to solve different contests to learn a new language (Kotlin), but I have a busy shedule (and cannot write regular contests in suitable time), so the only way for me is to train using virtual contests.
There is a great variety of contests on Codeforces (thanks to Mike!) and consequently it is not easy to decide which contests to solve.
I love random, but I have a better idea. Let's make the list of not anime-themed contests! But I need your help (in comments) to find them all...

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

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

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

Привет.

11 марта в Самарском университете состоялась ежегодная олимпиада по программированию, и мы снова выкладываем ее в тренировки Codeforces. Тренировка пройдет в воскресенье, 18 марта, в 11:00 MSK.

Этот контест уже третий год проводится личным. Поэтому просим всех тоже участвовать лично. Наиболее интересно должно быть фиолетовым и синим участникам.

Ну и как обычно,

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

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

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

Qualification Round has ended, but no blog on Codeforces yet. What happened to my Codeforces?

Main page: https://hashcode.withgoogle.com/

Judge system: https://hashcodejudge.withgoogle.com/

Our points: 10 / 176877 / 15824126 / 11808094 / 21465945, total score 49275052, 55th place.

How did you solve all the subtasks? I'm most interested in C and D.

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

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

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

Some weeks ago I read a Quora answer by I_love_Tanya_Romanova (link). The 4th paragraph attracted me, here is it's short content:

There are jokes about these typical problem statements: “Little Rohit got an array as a birthday present”. I’m also not getting why these trashy statements should be writtten instead of formal model of the task. It is awesome to have fictional statement when it makes sense, or when it comes from real life; it is at least funny to have stuff like problems I mentioned above. And I know that some of the platforms I mentioned are requiring problems with fictional statements and say that formal models are bad. Well, OK, “Parents asked little Chandan to perform following operations…”. May I go to some other site and solve normal problems, please? That’s a matter of taste — but for me this kind of statements is something that makes strong negative impression, and I think I’m not the only one.

I also don't like statements where characters were added just because there were no characters originally. You read such statement and think: "Why do they added this Alice with her birthday present? It has nothing to do with the problem".

I think there must be some rules that authors should use when they write a problem statement:

  1. If the problem comes from real life or from some situation that may appear in real life / fiction book / computer game — use the original statement. Those who will solve this problem will be clearly understand what's going on.
  2. If the problem originally had the formal statement (e.g. you have an array and you have to answer some queries, you have an array and you have to find a subarray with maximal xor / and / or, and so on): use formal statement.
  3. Never introduce a setting if the problem originally had formal statement.

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

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

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

I've just met a comment with a link to a problem statement. There was such text in the statement:

Soon the professor realized that reconstructing Anatoly’s code and the test tree from his output was not a simple task and that the result might be ambiguous. You will have to help her find all possible reconstructions of Anatoly’s code.

Don't you see something weird here? I think it should be:

Soon the professor realized that reconstructing Anatoly’s code and the test tree from his output was not a simple task and that the result might be ambiguous. You will have to help him find all possible reconstructions of Anatoly’s code.

or:

Soon the professor realized that reconstructing Anatoly’s code and the test tree from his output was not a simple task and that the result might be ambiguous. You will have to help them find all possible reconstructions of Anatoly’s code.

I know that people either use the gender that is more common for a person, e.g. he for drivers and she for nurses, or just use they (my English teacher said they is correct). I've wandered across Wikipedia (here is one of the links: https://en.wikipedia.org/wiki/English_personal_pronouns#Use_of_he.2C_she_and_it), but haven't found anything about preferrable usage of female pronouns.

However, I've read really a lot of English statements, and everywhere the female pronouns are used! For children and professors, for drivers and miners, for rabbits and foxes, for everything and everyone. Why?

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

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

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

Привет.

Некоторое время назад в Самарском университете состоялась ежегодная олимпиада по программированию, и мы снова выкладываем ее в тренировки Codeforces. Тренировка пройдет в субботу, 8 апреля, в 9:30 MSK. Сайт clist.by говорит, что пересечений с чем-то важным в это время нет.

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

Ну и как обычно,

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

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

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

Я совсем чуть-чуть заинтересованное лицо, но вроде бы стоит поднять немного шума, так как поведение организаторов чемпионата Урала выглядит так, будто им на все плевать.

Собственно, дело в том, что примерно неделю на этой страничке: http://acm.urfu.ru/chu/2017/ была информация, что отбор пройдет на опенкапе 2 апреля, но недавно ее поменяли, и на самом деле он пройдет 26 марта. Никому не кажется, что переносить дату отбора на неделю назад за неделю до начала — это очень подлый и неприемлемый поступок? Видя одну дату, люди начинают планировать свои дела, а спустя некоторое время все планы рушатся. Давайте может на завтра тогда перенесем? Там как раз какой-то контест от сборов МФТИ намечается. Вроде норм, да?

Например, у нас возникло пересечение с нашим ежегодным контестом (2012, 2013, 2014, 2015, 2016). Дата 26 марта довольно долго была свободна, но потом появляется опенкап, а затем на этот опенкап ставят отбор на чемпионат Урала. Если у вас крупное мероприятие — просто анонсируйте его заранее, чтобы организаторы мелких мероприятий могли подогнать даты. На самом деле я не верю, что команда из Самары прошла бы этот отбор, но, кажется, такие коллизии могут возникать где угодно и у кого угодно, и они не ограничиваются олимпиадами по программированию.

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

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

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

Всем привет.

Раунд скоро закончится, примерно через 1 час 30 минут после публикации этого поста. Стартовать вроде бы уже нельзя, если верить расписанию. Ну и конечно же, давайте обсуждать задачи здесь, бла-бла-бла, тому подобное.

Но мне больше интересно вот что: https://www.diffchecker.com/1154oPEl

Попробуйте угадать, какой из вердиктов на задачу X даст решение слева и справа.

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

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

Автор dalex, 7 лет назад, По-русски
  • Проголосовать: нравится
  • +147
  • Проголосовать: не нравится

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

Привет.

Некоторое время назад у нас в Самаре состоялась ежегодная олимпиада по программированию, и мы снова выкладываем ее в тренировки Codeforces. Тренировка пройдет в воскресенье, 17 апреля, в 11:00 MSK. Сайт clist.by говорит, что пересечений с чем-то важным в это время нет.

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

Ну и как обычно,

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

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

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

Всем привет.

Мне сегодня скинули вот такую ссылку: https://inclass.kaggle.com/c/dota-2-win-probability-prediction

В этом соревновании надо по первым 5 минутам лога игры определить вероятность победы Radiant (одной из команд). Я бы с удовольствием в этом поучаствовал, но, похоже, что это соревнование закрытое, ибо там выдается вот такое сообщение: This competition is private-entry. You can view but not participate.

Я никогда не был на Kaggle, но здесь наверняка есть люди, знакомые с Kaggle. Можете ли вы рассказать подробнее о подобных закрытых соревнованиях? Можно ли получить на них инвайт? Если да, можно ли участвовать командой и как правильно зарегаться?

UPD. Решение нашлось: надо зайти вот по этой ссылке: https://kaggle.com/join/coursera_ml_dota2_contest. После этого сообщение изменится на This competition is private-entry. You've been invited to participate.

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

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

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

Всем нравятся тренировки без мониторов? А даже если и с мониторами, то с кривыми логами сабмитов, автоматически сгенерированными Codeforces?

Я наконец-то выложил давно написанную утилитку для конвертации лога сабмитов. Называется она Standings Converter. На данный момент поддерживается только чтение из Ejudge-формата и запись в Testsys-формат, потому что это то направление конвертации, что нам приходится использовать каждые полгода, чтобы добавить очередной самарский контест в тренировки Codeforces. Но вы можете добавлять свои Parser-ы и Outputter-ы :)

Q: Я сгенерировал лог Testsys с помощью этой утилиты, как теперь его добавить в тренировку?
A: Назвать этот файл contest.dat, зайти по FTP в папку нужной тренировки, скопировать contest.dat в папку sandbox, а потом нажать в интерфейсе тренировки кнопку Обновить соревнование.

Q: У меня не установлен Maven и я не использую Java!!!11111
A: Пиши свой парсер :) Maven не совсем обязателен, можно просто запускать класс Main.

Q: import org.w3c.dom.*;
A: На момент написания я ничего другого не умел. Переписывать заново лень.

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

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

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

Всем привет!

Как уже многие знают, 13 сентября в СГАУ состоялся отборочный контест на четвертьфинал мира по программированию. Разумеется, мы не только развесили плакаты о мероприятии в стенах родного университета, но и сделали множество репостов в контакте, а также пообщались лично с тренерами других вузов, так что популяризация ACM в Самаре вышла на новый уровень. Помимо этого, в отличие от некоторых других организаторов некоторых других отборочных соревнований, мы неизменно выкладываем наши контесты в публичный доступ на тренировки Codeforces, где абсолютно любой желающий мог бы их решать. Так что уже в эту субботу, 14 ноября, в 11.00 MSK все желающие смогут проникнуться неповторимой атмосферой нашего отбора.

Контест пройдет в тренировках Codeforces, будет нерейтинговым и будет длиться 5 часов. Задачи готовили craus и Shlakoblock.

А вот полный список наших предыдущих контестов:

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

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

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

What's going on here? This contest was held two years ago. Just look at its id: it is 100187. Someone has managed to change its start date (and also to make it invisible for everyone but the author, which is fixed now), but how is it possible? Any permission settings? What if I go and reschedule all the contests in the gym? What if I hide them all? It must be a bug, admins, look into it, please.

P.S. Don't participate if you remember the problems.

UPD. Looks like gym vandals continue their work:

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

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