您的位置:首页 > 其它

【CodeForces】191C Fools and Roads

2012-08-23 11:17 330 查看
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#define MAXN 100010
#define MAXM 200010
using namespace std;
int first[MAXN], next[MAXM], v[MAXM], e;
bool vis[MAXN];
struct LCT {
int bef[MAXN], belong[MAXN];
int next[MAXN][2], pre[MAXN], key[MAXN], add[MAXN];
void Init() {
memset(next, 0, sizeof(next));
memset(pre, 0, sizeof(pre));
}
inline void PushDown(int x) {
if (add[x]) {
int a, b;
a = next[x][0], b = next[x][1];
if (a) {
add[a] += add[x];
key[a] += add[x];
}
if (b) {
add[b] += add[x];
key[b] += add[x];
}
add[x] = 0;
}
}
void Rotate(int x, int kind) {
int y, z;
y = pre[x];
z = pre[y];
PushDown(y);
PushDown(x);
next[y][!kind] = next[x][kind];
pre[next[x][kind]] = y;
next[z][next[z][1] == y] = x;
pre[x] = z;
next[x][kind] = y;
pre[y] = x;
}
void Splay(int x) {
int rt;
for (rt = x; pre[rt]; rt = pre[rt])
;
if (rt != x) {
bef[x] = bef[rt];
bef[rt] = 0;
PushDown(x);
while (pre[x]) {
if (next[pre[x]][0] == x)
Rotate(x, 1);
else
Rotate(x, 0);
}
}
}
void Access(int x) {
int father;
for (father = 0; x; x = bef[x]) {
Splay(x);
PushDown(x);
bef[next[x][1]] = x;
pre[next[x][1]] = 0;
next[x][1] = father;
pre[father] = x;
bef[father] = 0;
father = x;
}
}
void Update(int x, int y) {
Access(y);
for (y = 0; x; x = bef[x]) {
Splay(x);
if (!bef[x]) {
if (next[x][1]) {
key[next[x][1]]++;
add[next[x][1]]++;
}
if (y) {
key[y]++;
add[y]++;
}
return;
}
PushDown(x);
bef[next[x][1]] = x;
pre[next[x][1]] = 0;
next[x][1] = y;
pre[y] = x;
bef[y] = 0;
y = x;
}
}
int Query(int x) {
Splay(x);
return key[x];
}
} lct;
int INT() {
char ch;
int res;
while (ch = getchar(), !isdigit(ch))
;
for (res = ch - '0'; ch = getchar(), isdigit(ch);)
res = res * 10 + ch - '0';
return res;
}
inline void AddEdge(int x, int y) {
v[e] = y;
next[e] = first[x];
first[x] = e++;
}
void BFS(int x) {
int i, y;
queue<int> q;
memset(vis, false, sizeof(vis));
vis[x] = true;
q.push(x);
while (!q.empty()) {
x = q.front();
q.pop();
for (i = first[x]; i != -1; i = next[i]) {
y = v[i];
if (!vis[y]) {
lct.bef[y] = x;
lct.key[y] = lct.add[y] = 0;
lct.belong[i >> 1] = y;
vis[y] = true;
q.push(y);
}
}
}
}
int main() {
int n, i, q, x, y;
while (~scanf("%d", &n)) {
lct.Init();
memset(first, -1, sizeof(first));
for (e = 0, i = 1; i < n; i++) {
x = INT(), y = INT();
AddEdge(x, y);
AddEdge(y, x);
}
BFS(1);
q = INT();
while (q--) {
x = INT(), y = INT();
lct.Update(x, y);
}
for (i = 0; i < n - 2; i++)
printf("%d ", lct.Query(lct.belong[i]));
printf("%d\n", lct.Query(lct.belong[i]));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: