Gym 101611C
树链剖分,利用轻链到根节点小于logn的性质即可。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<bitset>
#include<map>
//#include<regex>
#include<cstdio>
#include <iomanip>
#pragma GCC optimize(2)
#define up(i,a,b) for(int i=a;i<b;i++)
#define dw(i,a,b) for(int i=a;i>b;i--)
#define upd(i,a,b) for(int i=a;i<=b;i++)
#define dwd(i,a,b) for(int i=a;i>=b;i--)
#define local
typedef long long ll;
typedef unsigned long long ull;
const double esp = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int inf = 1e9;
using namespace std;
ll read()
{
char ch = getchar(); ll x = 0, f = 1;
while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
return x * f;
}
typedef pair<int, int> pir;
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lrt root<<1
#define rrt root<<1|1
const int N = 100100;
const int NN = 1e6 + 10;
pir grp[NN];
int n;
vector<int>vec[NN];
int dfn[NN], son[NN], sz[NN], rk[NN];
int dp[NN];
int st = 0;
void dfs1(int u, int fa)
{
sz[u] = 1;
for (auto k : vec[u])
{
if (k == fa)continue;
dfs1(k, u);
sz[u] += sz[k];
if (son[u] == -1 || sz[son[u]] < sz[k])
son[u] = k;
}
}
void dfs2(int u, int fa, int dx, int dy)
{
dp[u] = dx;
grp[u] = make_pair(dx, dy);
for (auto k : vec[u])
{
if (k == fa || k == son[u])continue;
dfs2(k, u, dp[u] + 1, dy + 1);
dp[u] = max(dp[u], dp[k]);
}
if (son[u] != -1) {
dfs2(son[u], u, dp[u] + 1, dy);
dp[u] = max(dp[u], dp[son[u]]);
}
}
int main()
{
n = read();
int x, y;
memset(son, -1, sizeof(son));
up(i, 0, n - 1)
{
x = read(), y = read();
vec[x].push_back(y); vec[y].push_back(x);
}
dfs1(1, 0);
dfs2(1, 0, 1, 1);
upd(i, 1, n)printf("%d %d\n", grp[i].first, grp[i].second);
return 0;
}
橙橙橙