You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.5 KiB
66 lines
1.5 KiB
#include <bits/stdc++.h>
|
|
using namespace std;
|
|
const int N = 100010, M = N << 1;
|
|
#define int long long
|
|
#define endl "\n"
|
|
|
|
// 链式前向星
|
|
int e[M], h[N], idx, w[M], ne[M];
|
|
void add(int a, int b, int c = 0) {
|
|
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
|
|
}
|
|
|
|
int f[N], g[N], mod;
|
|
int pre[N], suff[N];
|
|
|
|
void dfs1(int u, int fa) {
|
|
f[u] = 1;
|
|
vector<int> son;
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
int v = e[i];
|
|
if (v == fa) continue;
|
|
dfs1(v, u);
|
|
f[u] = f[u] * (f[v] + 1) % mod;
|
|
son.push_back(v); // 将子节点加入集合,方便之后操作
|
|
}
|
|
int pre1 = 1;
|
|
int pre2 = 1;
|
|
|
|
// 预处理前缀积
|
|
for (int i = 0; i < son.size(); i++) {
|
|
pre[son[i]] = pre1;
|
|
pre1 = pre1 * (f[son[i]] + 1) % mod;
|
|
}
|
|
|
|
// 预处理后缀积
|
|
for (int i = son.size() - 1; i >= 0; i--) {
|
|
suff[son[i]] = pre2;
|
|
pre2 = pre2 * (f[son[i]] + 1) % mod;
|
|
}
|
|
}
|
|
|
|
void dfs2(int u, int fa) {
|
|
g[u] = (g[fa] * (pre[u] * suff[u] % mod) % mod + 1) % mod;
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
int v = e[i];
|
|
if (v == fa) continue;
|
|
dfs2(v, u);
|
|
}
|
|
}
|
|
|
|
signed main() {
|
|
// 初始化链式前向星
|
|
memset(h, -1, sizeof h);
|
|
|
|
int n;
|
|
cin >> n >> mod;
|
|
for (int i = 1; i < n; i++) {
|
|
int a, b;
|
|
cin >> a >> b;
|
|
add(a, b), add(b, a);
|
|
}
|
|
dfs1(1, -1);
|
|
g[1] = 1;
|
|
dfs2(1, -1);
|
|
for (int i = 1; i <= n; i++) cout << f[i] * g[i] % mod << endl;
|
|
} |