题目大意
求一棵树上是否存在路径长度为K的点对。是的话输出AYE 否则输出NAY
input
6
2 5 3 7 4 1 0
0
5 2 6 3 0
0
0
0
1
8
13
14
0
0
output
AYE
AYE
NAY
AYE
.
ideas
至于输入格式看代码吧,这道题的输入格式真的是一言难尽啊…
和上一道题目差不多,唯一的区别就是这个要处理的是a + b = m的个数,而上一题是要处理的a + b <= m的个数。我觉得点分治其实都差不多,关键要解决的问题就是怎么在合法的时间复杂度里处理出题目要求的东西。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn =1e5 + 100;
struct node {
int v, w;
};
vector<node> Edge[maxn];
int sonNum[maxn], sonMax[maxn], Node[maxn], dist[maxn];
bool vis[maxn];
int allNode, root, k, ans, cnt;
//sonNum该节点以及该节点子树的节点总个数
//sonMax 子树中最多节点的节点个数
//dist 到当前根的距离
//Node 用来储存所有距离点的数组
//root 重心
//a+b=m 的个数
void getroot(int now, int pre) {
sonNum[now] = 1; sonMax[now] = 0;
for(int i = 0; i < Edge[now].size(); i++) {
int to = Edge[now][i].v;
if(vis[to] || to == pre) continue;
getroot(to, now);
sonNum[now] += sonNum[to];
sonMax[now] = max(sonMax[now], sonNum[to]);
}
sonMax[now] = max(sonMax[now], allNode - sonNum[now]);
if(sonMax[root] > sonMax[now]) root = now;
}
int num = 0;
void getdist(int now, int pre, int length) {
dist[now] = length;
for(int i = 0; i < Edge[now].size(); i++) {
int to = Edge[now][i].v, w = Edge[now][i].w;
if(vis[to] || to == pre) continue;
getdist(to, now, length + w);
}
Node[cnt++] = dist[now];
}
int cal(int now, int length) {
cnt = 0;
getdist(now, 0, length);
sort(Node, Node + cnt);
int num = 0;
for(int l = 0, r = cnt - 1; l < r;) {
if(Node[l] + Node[r] == k) {
if(Node[l] == Node[r]) {
num += (r - l + 1) * (r - l) / 2;
break;
}
else {
int i = l, j = r;
while(Node[i] == Node[l]) i++;
while(Node[j] == Node[r]) j--;
num += (i - l) * (r - j);
l = i, r = j;
}
}
else if(Node[l] + Node[r] < k) l++;
else r--;
}
return num;
}
void solve(int now) {
ans += cal(now, 0);
vis[now] = true;
for(int i = 0; i < Edge[now].size(); i++) {
int to = Edge[now][i].v, w = Edge[now][i].w;
if(vis[to]) continue;
ans -= cal(to, w);
sonMax[0] = allNode = sonNum[to];
getroot(to, root = 0);
solve(root);
}
}
int main()
{
int n;
while(~scanf("%d", &n) && n) {
for(int i = 0; i <= n; i++) Edge[i].clear();
for(int i = 1; i <= n; i++) {
int v, w;
while(~scanf("%d", &v) && v) {
scanf("%d", &w);
Edge[i].push_back((node) {v, w});
Edge[v].push_back((node) {i, w});
}
}
while(~scanf("%d", &k) && k) {
ans = 0;
for(int i = 0; i <= n; i++) vis[i] = false;
sonMax[0] = allNode = n;
getroot(1, root = 0);
solve(root);
if(ans > 0) printf("AYE\n");
else printf("NAY\n");
}
printf(".\n");
}
}