一本通1514:【例 2】最大半连通子图

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 100;
const int M = 2e6 + 100;
struct node {
    int to, next;
} e1[M], e2[M];
int n, m, mod, tot1, tot2, top, num, scc, res, tmp, x, y;
int head1[N], head2[N], dfn[N], low[N], sta[N], belong[N];
int siz[N], use[N], f[N], g[N];
bool vis[N];
void add(int u, int v) {
    e1[++tot1] = {v, head1[u]};
    head1[u] = tot1;
}
void Add(int u, int v) {
    e2[++tot2] = {v, head2[u]};
    head2[u] = tot2;
}
void tarjan(int x) {
    dfn[x] = low[x] = ++num;
    sta[++top] = x;
    vis[x] = 1;

    for (int i = head1[x]; i; i = e1[i].next) {
        int y = e1[i].to;

        if (!dfn[y]) {
            tarjan(y);
            low[x] = min(low[x], low[y]);
        } else if (vis[y])
            low[x] = min(low[x], dfn[y]);
    }

    if (dfn[x] == low[x]) {
        scc++;
        int k = -1;

        while (k != x) {
            k = sta[top--];
            belong[k] = scc;
            siz[scc]++;
            vis[k] = 0;
        }
    }
}
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m >> mod;

    for (int i = 1; i <= m; i++) {
        cin >> x >> y;
        add(x, y);
    }

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

    for (int x = 1; x <= n; x++) {
        f[x] = siz[x];
        g[x] = 1;

        for (int i = head1[x]; i; i = e1[i].next) {
            int y = e1[i].to;

            if (belong[x] != belong[y])
                Add(belong[x], belong[y]);
        }
    }

    for (int x = scc; x >= 1; x--) {
        for (int i = head2[x]; i; i = e2[i].next) {
            int y = e2[i].to;

            if (use[y] == x)
                continue;

            use[y] = x;

            if (f[y] < f[x] + siz[y]) {
                f[y] = f[x] + siz[y];
                g[y] = g[x];
            } else if (f[y] == f[x] + siz[y])
                (g[y] += g[x]) %= mod;
        }
    }

    for (int i = 1; i <= scc; i++) {
        if (f[i] > res) {
            res = f[i];
            tmp = g[i];
        } else if (f[i] == res)
            (tmp += g[i]) %= mod;
    }

    cout << res << '\n' << tmp;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值