这个题和POJ 1741类似。。。。只不过求的是在树上是否存在路径长度等于K的路径。。。解法也是类似的。。。就在分治中求出路径长度等于k的路径个数,如果是根节点就加上,儿子节点就减去。总复杂度m*n*log(n)*log(n)
#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 10005 #define maxm 20005 #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; }*H[maxn], E[maxm], *edges; vector<int> dis; bool done[maxn]; int size[maxn]; int mx[maxn]; int a[105]; int b[105]; int root, n, m, nsize; void addedges(int u, int v, int w) { edges->v = v; edges->w = w; edges->next = H[u]; H[u] = edges++; } void init() { edges = E; memset(b, 0, sizeof b); memset(H, 0, sizeof H); memset(done, 0, sizeof done); } void read() { int v, w; for(int i = 1; i <= n; i++) { scanf("%d", &v); if(v == 0) continue; scanf("%d", &w); addedges(i, v, w); addedges(v, i, w); i--; } m = 0; while(scanf("%d", &w), w != 0) a[++m] = w; } void getroot(int u, int fa) { size[u] = 1, mx[u] = 0; for(Edge *e = H[u]; e; e = e->next) if(!done[e->v] && e->v != fa) { int v = e->v; getroot(v, u); size[u] += size[v]; mx[u] = max(mx[u], size[v]); } mx[u] = max(mx[u], nsize - size[u]); if(mx[u] < mx[root]) root = u; } void getdis(int u, int fa, int dist) { dis.push_back(dist); for(Edge *e = H[u]; e; e = e->next) if(!done[e->v] && fa != e->v) { int v = e->v, w = e->w; getdis(v, u, dist + w); } } void calc(int u, int fa, int dist, int flag) { dis.clear(); getdis(u, fa, dist); sort(dis.begin(), dis.end()); for(int i = 1; i <= m; i++) { for(int l = 0, r = dis.size() - 1; l < r; ) { if(dis[l] + dis[r] == a[i]) { b[i] += flag; if(r && dis[r-1] == dis[r]) r--; else l++; } else if(dis[l] + dis[r] > a[i]) r--; else l++; } } } void solve(int u) { calc(u, 0, 0, 1); done[u] = true; for(Edge *e = H[u]; e; e = e->next) if(!done[e->v]) { int v = e->v, w = e->w; calc(v, u, w, -1); mx[0] = nsize = size[v]; getroot(v, root = 0); solve(root); } } void work() { mx[0] = nsize = n; getroot(1, root = 0); solve(root); for(int i = 1; i <= m; i++) if(b[i]) printf("AYE\n"); else printf("NAY\n"); printf(".\n"); } int main() { while(scanf("%d", &n), n != 0) { init(); read(); work(); } return 0; }