根据每次的加点删点求对答案的贡献。。。
#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 100005
#define maxm 200005
#define eps 1e-7
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid
#define rson o<<1 | 1, mid+1, R
#define pii pair<int, int>
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
// head
struct Edge
{
int v, w;
Edge *next;
}E[maxm], *H[maxn], *edges;
const int M = 20;
set<pii> s;
set<pii>::iterator t1, t2;
int anc[maxn][20];
bool used[maxn];
int dep[maxn];
int in[maxn];
int dis[maxn];
int n, m, dfs_clock;
void init()
{
dfs_clock = 0;
edges = E;
memset(H, 0, sizeof H);
memset(used, 0, sizeof used);
}
void addedges(int u, int v, int w)
{
edges->v = v;
edges->w = w;
edges->next = H[u];
H[u] = edges++;
}
void dfs(int u, int fa)
{
anc[u][0] = fa;
in[u] = ++dfs_clock;
for(Edge *e = H[u]; e; e = e->next) if(e->v != fa) {
int v = e->v, w = e->w;
dis[v] = dis[u] + w;
dep[v] = dep[u] + 1;
dfs(v, u);
}
}
int to(int u, int d)
{
for(int i = M - 1; i >= 0; i--) if(dep[anc[u][i]] >= d) u = anc[u][i];
return u;
}
int lca(int u, int v)
{
if(dep[u] < dep[v]) swap(u, v);
u = to(u, dep[v]);
for(int i = M - 1; i >= 0; i--) if(anc[u][i] != anc[v][i]) u = anc[u][i], v = anc[v][i];
return u == v ? u : anc[u][0];
}
void work()
{
int u, v, w;
scanf("%d%d", &n, &m);
for(int i = 1; i < n; i++) {
scanf("%d%d%d", &u, &v, &w);
addedges(u, v, w);
addedges(v, u, w);
}
dfs(1, 1);
for(int j = 1; j < M; j++)
for(int i = 1; i <= n; i++)
anc[i][j] = anc[anc[i][j-1]][j-1];
int ans = 0, op;
s.clear();
for(int i = 1; i <= m; i++) {
scanf("%d%d", &op, &u);
if(op == 1) {
if(used[u]) goto print;
else used[u] = 1;
if(s.empty()) {
s.insert(mp(in[u], u));
goto print;
}
t1 = s.lower_bound(mp(in[u], u));
t2 = t1, t2--;
int a, b;
if(t1 == s.end() || t1 == s.begin()) t2 = s.begin(), t1 = --s.end();
a = t2->second, b = t1->second;
ans += dis[u] + dis[lca(a, b)] - dis[lca(u, b)] - dis[lca(u, a)];
s.insert(mp(in[u], u));
}
else {
if(!used[u]) goto print;
else used[u] = 0;
s.erase(mp(in[u], u));
t1 = s.lower_bound(mp(in[u], u));
t2 = t1, t2--;
int a, b;
if(t1 == s.end() || t1 == s.begin()) t2 = s.begin(), t1 = --s.end();
a = t2->second, b = t1->second;
ans -= dis[u] + dis[lca(a, b)] - dis[lca(u, a)] - dis[lca(u, b)];
}
print:
printf("%d\n", ans);
}
}
int main()
{
int _;
scanf("%d", &_);
for(int i = 1; i <= _; i++) {
printf("Case #%d:\n", i);
init();
work();
}
return 0;
}