|
|
|
@ -2,68 +2,53 @@
|
|
|
|
|
using namespace std;
|
|
|
|
|
#define int long long
|
|
|
|
|
#define endl "\n"
|
|
|
|
|
const int N = 100010;
|
|
|
|
|
|
|
|
|
|
const int N = 100010, M = N << 1;
|
|
|
|
|
// 链式前向星
|
|
|
|
|
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];
|
|
|
|
|
int n, mod;
|
|
|
|
|
int pro1[N], pro2[N];
|
|
|
|
|
|
|
|
|
|
void dfs1(int u, int fa) {
|
|
|
|
|
f[u] = 1;
|
|
|
|
|
vector<int> edgeson;
|
|
|
|
|
int n, m;
|
|
|
|
|
|
|
|
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
|
|
|
int v = e[i];
|
|
|
|
|
if (v == fa) continue;
|
|
|
|
|
dfs1(v, u);
|
|
|
|
|
vector<int> s[N];
|
|
|
|
|
int dp[N], pd[N];
|
|
|
|
|
|
|
|
|
|
f[u] = f[u] * (f[v] + 1) % mod;
|
|
|
|
|
edgeson.push_back(v); // 将子节点加入集合,方便之后操作
|
|
|
|
|
void dfs1(int x, int fa) {
|
|
|
|
|
for (int i : s[x]) {
|
|
|
|
|
if (i != fa) {
|
|
|
|
|
dfs1(i, x);
|
|
|
|
|
dp[x] = dp[x] * (dp[i] + 1) % m;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
int pre1 = 1;
|
|
|
|
|
int pre2 = 1;
|
|
|
|
|
|
|
|
|
|
for (int i = 0; i < edgeson.size(); i++) {
|
|
|
|
|
pro1[edgeson[i]] = pre1;
|
|
|
|
|
pre1 = pre1 * (f[edgeson[i]] + 1) % mod;
|
|
|
|
|
} // 预处理前缀积
|
|
|
|
|
|
|
|
|
|
for (int i = edgeson.size() - 1; i >= 0; i--) {
|
|
|
|
|
pro2[edgeson[i]] = pre2;
|
|
|
|
|
pre2 = pre2 * (f[edgeson[i]] + 1) % mod;
|
|
|
|
|
} // 预处理后缀积
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void dfs2(int u, int fa) {
|
|
|
|
|
if (fa == 0)
|
|
|
|
|
g[u] = 1; // 特判根节点
|
|
|
|
|
else
|
|
|
|
|
g[u] = (g[fa] * (pro1[u] * pro2[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);
|
|
|
|
|
}
|
|
|
|
|
void dfs2(int x, int fa) {
|
|
|
|
|
int t = pd[x];
|
|
|
|
|
for (int i : s[x])
|
|
|
|
|
if (i != fa)
|
|
|
|
|
pd[i] = pd[i] * t % m;
|
|
|
|
|
t = 1;
|
|
|
|
|
for (int i : s[x])
|
|
|
|
|
if (i != fa)
|
|
|
|
|
pd[i] = pd[i] * t % m, t = t * (dp[i] + 1) % m;
|
|
|
|
|
t = 1;
|
|
|
|
|
reverse(s[x].begin(), s[x].end());
|
|
|
|
|
for (int i : s[x])
|
|
|
|
|
if (i != fa)
|
|
|
|
|
pd[i] = pd[i] * t % m, t = t * (dp[i] + 1) % m;
|
|
|
|
|
for (int i : s[x])
|
|
|
|
|
if (i != fa) {
|
|
|
|
|
++pd[i];
|
|
|
|
|
dfs2(i, x);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
signed main() {
|
|
|
|
|
// 初始化链式前向星
|
|
|
|
|
memset(h, -1, sizeof h);
|
|
|
|
|
cin >> n >> mod;
|
|
|
|
|
|
|
|
|
|
signed main() {
|
|
|
|
|
cin >> n >> m;
|
|
|
|
|
for (int i = 1; i <= n; i++) dp[i] = pd[i] = 1;
|
|
|
|
|
for (int i = 1; i < n; i++) {
|
|
|
|
|
int a, b;
|
|
|
|
|
cin >> a >> b;
|
|
|
|
|
add(a, b), add(b, a);
|
|
|
|
|
s[a].push_back(b), s[b].push_back(a);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
dfs1(1, 0);
|
|
|
|
|
dfs2(1, 0);
|
|
|
|
|
for (int i = 1; i <= n; i++) cout << f[i] * g[i] % mod << endl;
|
|
|
|
|
for (int i = 1; i <= n; ++i) cout << dp[i] * pd[i] % m << endl;
|
|
|
|
|
}
|