【LG3320】[SDOI2015]寻宝游戏
题面
题解
不需要建虚树的虚树2333。。。
贪心地想一下,起始节点肯定是在关键点上,访问顺序就是(dfs)序。
那么对于每次询问,
[Ans=dis(S_1,S_s)+sum_{i=1}^{s-1}dis(S_i,S_{i+1})
]
用(set)维护一下就好了
代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <set>
using namespace std;
inline int gi() {
register int data = 0, w = 1;
register char ch = 0;
while (!isdigit(ch) && ch != '-') ch = getchar();
if (ch == '-') w = -1, ch = getchar();
while (isdigit(ch)) data = 10 * data + ch - '0', ch = getchar();
return w * data;
}
typedef long long ll;
const int MAX_N = 1e5 + 5;
struct Graph { int to, next, cost; } e[MAX_N << 1];
int fir[MAX_N], e_cnt;
void clearGraph() { memset(fir, -1, sizeof(fir)); }
void Add_Edge(int u, int v, int w) { e[e_cnt] = (Graph){v, fir[u], w}; fir[u] = e_cnt++; }
int N, M;
ll dis[MAX_N], ans;
int dep[MAX_N], size[MAX_N], top[MAX_N], son[MAX_N], fa[MAX_N], dfn[MAX_N], tim;
void dfs1(int x) {
size[x] = 1, dep[x] = dep[fa[x]] + 1;
for (int i = fir[x]; ~i; i = e[i].next) {
int v = e[i].to; if (v == fa[x]) continue;
dis[v] = dis[x] + e[i].cost;
fa[v] = x, dfs1(v), size[x] += size[v];
if (size[v] > size[son[x]]) son[x] = v;
}
}
void dfs2(int x, int tp) {
top[x] = tp, dfn[x] = ++tim;
if (son[x]) dfs2(son[x], tp);
for (int i = fir[x]; ~i; i = e[i].next) {
int v = e[i].to; if (v == fa[x] || v == son[x]) continue;
dfs2(v, v);
}
}
int LCA(int u, int v) {
while (top[u] != top[v]) {
if (dep[top[u]] < dep[top[v]]) swap(u, v);
u = fa[top[u]];
}
return dep[u] < dep[v] ? u : v;
}
ll DIS(int x, int y) { return dis[x] + dis[y] - 2ll * dis[LCA(x, y)]; }
struct cmp { bool operator () (int x, int y) const { return dfn[x] < dfn[y]; } } ;
set<int, cmp> s = set<int, cmp>(cmp());
set<int, cmp> :: iterator ite;
bool vis[MAX_N];
int main () {
#ifndef ONLINE_JUDGE
freopen("cpp.in", "r", stdin);
#endif
clearGraph();
N = gi(), M = gi();
for (int i = 1; i < N; i++) {
int u = gi(), v = gi(), w = gi();
Add_Edge(u, v, w), Add_Edge(v, u, w);
}
dfs1(1), dfs2(1, 1);
while (M--) {
int x = gi();
if (vis[x]) {
ite = s.find(x);
if (s.size() < 3) { ans = 0; goto P1; }
int pre, nxt;
if (ite == s.begin()) pre = *--s.end();
else pre = *(--ite), ++ite;
if (ite == --s.end()) nxt = *s.begin();
else nxt = *(++ite), --ite;
ans -= DIS(pre, x) + DIS(x, nxt) - DIS(pre, nxt);
P1 :
s.erase(ite);
} else {
ite = s.insert(x).first;
if (s.size() == 1) goto P2;
int pre, nxt;
if (ite == s.begin()) pre = *--s.end();
else pre = *(--ite), ++ite;
if (ite == --s.end()) nxt = *s.begin();
else nxt = *(++ite), --ite;
ans += DIS(pre, x) + DIS(x, nxt) - DIS(pre, nxt);
P2: ;
}
vis[x] ^= 1;
printf("%lld
", ans);
}
return 0;
}