小A的最短路
小A的最短路
思路
樹上問題求兩個點的最短距離,顯然能用lcalcalca來進行lognlog_nlogn?的查詢,引入了兩個無邊權的點,所以我們的路勁就可以規劃成三種x?>y,x?>u?>v?>y,x?>v?>u>?yx -> y, x -> u -> v -> y, x -> v -> u >- yx?>y,x?>u?>v?>y,x?>v?>u>?y,只要在這三個當中取一個最小值就行了。接下來就是考慮求lcalcalca了,有一種較為快速的求lcalcalca的在線方法,那就是樹鏈剖分,于是套上去(個人認為樹剖求lcalcalca較為好寫),然后就可以開始最短路求解了。
代碼
/*Author : lifehappy */ #pragma GCC optimize(2) #pragma GCC optimize(3) #include #define mp make_pair #define pb push_back #define endl '\n'using namespace std;typedef long long ll; typedef unsigned long long ull; typedef pair pii;const double pi = acos(-1.0); const double eps = 1e-7; const int inf = 0x3f3f3f3f;inline ll read() {ll f = 1, x = 0;char c = getchar();while(c '9') {if(c == '-') f = -1;c = getchar();}while(c >= '0' && c <= '9') {x = (x << 1) + (x << 3) + (c ^ 48);c = getchar();}return f * x; }void print(ll x) {if(x < 10) {putchar(x + 48);return ;}print(x / 10);putchar(x % 10 + 48); }const int N = 3e5 + 10;int sz[N], son[N], fa[N], dep[N], top[N], n, m;int head[N], to[N << 1], nex[N << 1], cnt = 1;void add(int x, int y) {to[cnt] = y;nex[cnt] = head[x];head[x] = cnt++; }void dfs1(int rt, int f) {fa[rt] = f, sz[rt] = 1;dep[rt] = dep[f] + 1;for(int i = head[rt]; i; i = nex[i]) {if(to[i] == f) continue;dfs1(to[i], rt);sz[rt] += sz[to[i]];if(!son[rt] || sz[to[i]] > sz[son[rt]]) son[rt] = to[i];} }void dfs2(int rt, int tp) {top[rt] = tp;if(!son[rt]) return ;dfs2(son[rt], tp);for(int i = head[rt]; i; i = nex[i]) {if(to[i] == fa[rt] || to[i] == son[rt]) continue;dfs2(to[i], to[i]);} }int lca(int x, int y) {while(top[x] != top[y]) {if(dep[top[x]] < dep[top[y]]) swap(x, y);x = fa[top[x]];}return dep[x] < dep[y] ? x : y; }int dis(int x, int y) {return dep[x] + dep[y] - 2 * dep[lca(x, y)]; }int main() {// freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);//ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);n = read();for(int i = 1; i < n; i++) {int x = read(), y = read();add(x, y);add(y, x);}int u = read(), v = read();dfs1(1, 0);dfs2(1, 1);m = read();for(int i = 1; i <= m; i++) {int x = read(), y = read();printf("%d\n", min({dis(x, y), dis(x, u) + dis(v, y), dis(x, v) + dis(u, y)}));}return 0; }總結
- 上一篇: 减肥期间几点睡觉
- 下一篇: HDU 2588 GCD(欧拉函数)