QOJ.ac

QOJ

Limite de temps : 3 s Limite de mémoire : 512 MB Points totaux : 100 Hackable ✓

#6274. Путешествие по миру

Statistiques

Дан неориентированный простой связный граф с $n$ вершинами и $m-1$ ребром. Веса этих ребер представляют собой перестановку чисел от $2$ до $m$.

Весом пути называется произведение весов всех ребер, входящих в этот путь. Каков максимально возможный вес пути из $s$ в $t$, не превышающий $m$? Заметьте, что путь может проходить через одну и ту же вершину или ребро несколько раз.

Вам необходимо ответить на несколько запросов.

Входные данные

В первой строке заданы три целых положительных числа $n, m, q$.

В следующих $m-1$ строках заданы по два целых положительных числа $u, v$, обозначающих вершины, соединенные ребром с весом $2, 3, \dots, m$ соответственно.

В следующих $q$ строках заданы по два целых положительных числа $s, t$, описывающих запрос.

Выходные данные

Выведите $q$ строк, по одному числу в каждой. Если существует путь с весом, не превышающим $m$, выведите его максимальное значение, в противном случае выведите $-1$.

Пример данных

4 5 10
1 2
2 3
3 4
4 1
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4
4
2
-1
5
4
3
-1
1
4
1

Подзадачи

Для $100\%$ данных гарантируется, что $2\leq n\leq m\leq 5\times 10^5$ и $1\leq q\leq 5\times 10^5$.

Для теста $1$ гарантируется $m\leq 10$.

Для теста $2$ гарантируется $m\leq 100$.

Для тестов $3\sim 4$ гарантируется $m\leq 10^3$.

Для тестов $5\sim 6$ гарантируется $m\leq 10^4$.

Для тестов $7\sim 9$ гарантируется $m\leq 10^5$.

Для теста $10$ особых ограничений нет.

Примечание

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

using u32 = unsigned;
struct IO_Tp
{
    const static int _I_Buffer_Size = 30 << 20;
    char _I_Buffer[_I_Buffer_Size], *_I_pos = _I_Buffer;

    const static int _O_Buffer_Size = 8 << 20;
    char _O_Buffer[_O_Buffer_Size], *_O_pos = _O_Buffer;

    u32 m[10000];

    IO_Tp()
    {
//        freopen("tour.in", "r", stdin);
//        freopen("tour.out", "w", stdout);
        constexpr u32 e0 = '\0\0\0\1', e1 = '\0\0\1\0', e2 = '\0\1\0\0', e3 = '\1\0\0\0';
        int x = 0;
        for (u32 i = 0, c0 = '0000'; i != 10; ++i, c0 += e0)
            for (u32 j = 0, c1 = c0; j != 10; ++j, c1 += e1)
                for (u32 k = 0, c2 = c1; k != 10; ++k, c2 += e2)
                    for (u32 l = 0, c3 = c2; l != 10; ++l, c3 += e3)
                        m[x++] = c3;

        fread(_I_Buffer, 1, _I_Buffer_Size, stdin);
    }
    ~IO_Tp() { fwrite(_O_Buffer, 1, _O_pos - _O_Buffer, stdout); }

    IO_Tp &operator>>(int &res)
    {
        while (!isdigit(*_I_pos))
            ++_I_pos;
        res = *_I_pos++ - '0';
        while (isdigit(*_I_pos))
            res = res * 10 + (*_I_pos++ - '0');
        return *this;
    }

    IO_Tp &operator<<(int x)
    {
        if (x == -1)
        {
            *_O_pos++ = '-';
            *_O_pos++ = '1';
            return *this;
        }
        if (x == 0)
        {
            *_O_pos++ = '0';
            return *this; 
        }
        static char _buf[35];
        char *_pos = _buf + 35;
        while (x >= 10000)
            *--reinterpret_cast<u32 *&>(_pos) = m[x % 10000], x /= 10000;
        *--reinterpret_cast<u32 *&>(_pos) = m[x];
        _pos += (x < 1000) + (x < 100) + (x < 10);
        _O_pos = std::copy(_pos, _buf + 35, _O_pos);
        return *this;
    }

    IO_Tp &operator<<(char ch)
    {
        *_O_pos++ = ch;
        return *this;
    }
} IO;

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.