tarjan过不了hack数据,求助
查看原帖
tarjan过不了hack数据,求助
782850
FaintCloudy楼主2024/8/12 04:50

有人知道怎么过hack数据吗

#include <iostream>
#include <bits/stdc++.h>
typedef long long LL;
const int N = 3e5 + 10, M = 998244353;
using namespace std;
LL pre[N][55], ans[N];
int deep[N], n, m, u, v, k, f[N], vis[N];
int find(int x) {
    return x == f[x] ? x : f[x] = find(f[x]);
}
LL quickPow(long long base, long long exponent, long long mod) {
    long long result = 1;
    while (exponent > 0) {
        if (exponent & 1) {
            result = (result * base) % mod;
        }
        base = (base * base) % mod;
        exponent >>= 1;
    }
    return result;
}
LL rpow(LL a1, LL a2) {
    return pre[a1][a2] ? pre[a1][a2] : pre[a1][a2] = ((LL) quickPow(a1, a2, M)) % M;
}
vector<int> g[N];
struct Query {
    int to, power, id;
};
vector<Query> q[N];
void tarjan(int x) {
    vis[x] = 1;
    for (int y : g[x]) {
        if (!vis[y]) {
            deep[y] = deep[x] + 1;
            tarjan(y);
            f[y] = x;
        }
    }
    for (Query query : q[x]) {
        int y = query.to;
        int p = query.power;
        if (vis[y]) {
            int lca = find(y);
            LL result = 0;
            //printf("current lca = %d, deep[%d] = %d, k = %d\n", lca, lca, deep[lca], p);
            for (int i = deep[lca];i<=deep[x];i++) {
                //printf("i = %d, result += %lld\n", i, rpow(i, p));
                result += rpow(i, p);
                result %= M;
            }
            for (int i = deep[lca] + 1;i<=deep[y];i++) {
                //printf("i = %d, result += %lld\n", i, rpow(i, p));
                result += rpow(i, p);
                result %= M;
            }
            ans[query.id] = result;
        }
    }
}
int main() {

    scanf("%d", &n);
    for (int i = 1;i<=n-1;i++) {
        f[i] = i;
        scanf("%d%d", &u, &v);
        g[u].push_back(v), g[v].push_back(u);
    }
    f[n] = n;
    scanf("%d", &m);
    for (int i = 1;i<=m;i++) {
        scanf("%d%d%d", &u, &v, &k);
        q[u].push_back({v, k, i});
        q[v].push_back({u, k, i});
    }
    deep[1] = 0;
    tarjan(1);
    for (int i = 1;i<=m;i++)
        printf("%lld\n", ans[i]);
    return 0;
}

2024/8/12 04:50
加载中...