1836F - Doctor's Brown Hypothesis - CodeForces Solution


dfs and similar dfs and similar graphs graphs math math number theory number theory

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>

using namespace std;

const int N = 100005;
int n, m;
int dfn[N], low[N], d[N];
int st[N], top, tot, g[N];
bool in[N];
long long k, ans;
vector<int> to[N];
int sum[N];

int gcd(int n, int m) { return !m ? n : gcd(m, n % m); }

void dfs(int i)
{
    low[i] = dfn[i] = ++tot;
    st[++top] = i, in[i] = 1;

    for (int j : to[i])
    {
        if (!dfn[j])
        {
            d[j] = d[i] + 1;
            dfs(j);
            low[i] = min(low[i], low[j]);
            continue;
        }

        if (!in[j])
        {
            continue;
        }

        low[i] = min(low[i], low[j]);
        g[i] = gcd(g[i], abs(d[i] + 1 - d[j]));
    }

    if (low[i] == dfn[i])
    {
        int len = 0, x;
        vector<int> tp;
        do
        {
            x = st[top--];
            in[x] = 0;
            len = gcd(len, g[x]);
            tp.push_back(x);
        } while (x != i);

        if (len == 0)
        {
            return;
        }

        int gu = k % len;
        for (int j : tp)
        {
            sum[d[j] % len]++;
        }

        if (!gu)
        {
            for (int t = 0; t != len; t++)
            {
                int x = sum[t];
                ans += 1ll * x * (x + 1) / 2;
            }
        }
        else if (gu * 2 == len)
        {
            for (int t = 0; t != gu; t++)
            {
                ans += 1ll * sum[t] * sum[(t + gu) % len];
            }
        }

        for (int t = 0; t != len; t++)
        {
            sum[t] = 0;
        }
    }
}

int main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    cin >> n >> m >> k;
    while (m--)
    {
        int x, y;
        cin >> x >> y;
        to[x].push_back(y);
    }

    for (int i = 1; i <= n; i++)
    {
        if (!dfn[i])
        {
            dfs(i);
        }
    }

    cout << ans << endl;
}


Comments

Submit
0 Comments
More Questions

1102A - Integer Sequence Dividing
630B - Moore's Law
1004A - Sonya and Hotels
1680B - Robots
1690A - Print a Pedestal (Codeforces logo)
1295A - Display The Number
1077A - Frog Jumping
1714G - Path Prefixes
1369C - RationalLee
289B - Polo the Penguin and Matrix
1716A - 2-3 Moves
1670B - Dorms War
1716B - Permutation Chain
987A - Infinity Gauntlet
1676G - White-Black Balanced Subtrees
1716D - Chip Move
1352F - Binary String Reconstruction
1487B - Cat Cycle
1679C - Rooks Defenders
56A - Bar
1694B - Paranoid String
35A - Shell Game
1684A - Digit Minimization
43B - Letter
1017A - The Rank
1698B - Rising Sand
235A - LCM Challenge
1075B - Taxi drivers and Lyft
1562A - The Miracle and the Sleeper
1216A - Prefixes