點分治學習筆記

點分治學習筆記


模板題[洛谷P3806]

題意:給定一棵有n個點的樹,詢問樹上距離爲k的點對是否存在。c++

作法:對於一個點\(u\),樹上全部的路徑能夠分爲兩類,一類是通過點\(u\),另外一類是沒有通過點\(u\),即整條路徑位於\(u\)的某個子樹中。那麼咱們就能夠對於點\(u\)統計出通過他的路徑是否能夠構成\(k\),而後刪去點\(u\),對於每一個子樹的挑一個點做爲根\(v\),重複一樣的操做。這樣咱們就統計出了全部的路徑。
而後咱們注意到,若是這棵樹是一條鏈,最壞的狀況複雜度會降低爲\(O(n^2)\),爲了解決這個問題,咱們每次選取當前這棵樹的重心做爲根來分治,就能夠將最壞複雜度降爲\(O(nlogn)\),爲了寫起來方便個人代碼多了一個\(log\)git

Code:學習

#include <bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define pb push_back
#define Pii pair<int,int>
#define x first
#define y second
const int N = 10005;
template <class T> inline void read(T &x) {
    x = 0; T f = 1; char c = getchar();
    while(!isdigit(c)) { if(c == '-') f = -1; c = getchar(); }
    while(isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); }
    x *= f;
}
using namespace std;
int n, m, K[111], Ans[111];
struct edge{int e, w, nxt;} E[N << 1];
int h[N], cc;
void add(int u, int v, int w) {
    E[cc].e = v; E[cc].w = w;
    E[cc].nxt = h[u]; h[u] = cc; ++cc;
}
int used[N], sz[N], mxp[N];
map<int,int> dep;
set<int> S;
int idx, MN;
void dfs(int u, int pre, int num) {
    sz[u] = 1; mxp[u] = 0;
    for(int i = h[u]; ~i; i = E[i].nxt) if(!used[E[i].e] && E[i].e != pre){
        int v = E[i].e;
        dfs(v, u, num);
        sz[u] += sz[v];
        mxp[u] = max(mxp[u], sz[v]);
    }
    mxp[u] = max(mxp[u], num-sz[u]);
    if(mxp[u] < MN) MN = mxp[u], idx = u;
}
int fdrt(int u,int sum) {
    idx = 0, MN = __INT_MAX__;
    dfs(u,0,sum);
    return idx;
}
void bfs(int u, int w) {
    dep[u] = w;
    queue<int> q; q.push(u);
    while(!q.empty()) {
        int u = q.front(); q.pop();
        for(int i = h[u]; ~i ; i = E[i].nxt) if(!used[E[i].e] && dep.find(E[i].e) == dep.end()) {
            int v = E[i].e;
            dep[v] = dep[u] + E[i].w;
            q.push(v);
        }
    }
}
int M[N];
void solve(int u) {
    used[u] = 1; S.clear(); S.insert(0);
    for(int i = h[u]; ~i; i = E[i].nxt) if(!used[E[i].e]) {
        int v =  E[i].e, w = E[i].w;
        dep.clear();
        bfs(v,w);
        for(auto A: dep) {
            for(int j = 1; j <= m; ++j) {
                if(S.find(K[j] - A.y) != S.end()) Ans[j] |= 1;
            }
        }
        for(auto A: dep) S.insert(A.y);
        M[v] = dep.size();
    }
    for(int i = h[u]; ~i; i = E[i].nxt) if(!used[E[i].e]) {
        solve( fdrt(E[i].e, M[E[i].e]) );
    }
}
int main() {
    read(n); read(m); int u, v, w; memset(h, -1, sizeof(h));
    rep(i,2,n) read(u), read(v), read(w), add(u,v,w), add(v,u,w);
    rep(i,1,m) read(K[i]);
    int rt = fdrt(1,n);
    solve(rt);
    rep(i,1,m) puts(Ans[i] ? "AYE" : "NAY");
}
相關文章
相關標籤/搜索