题目大意:和poj 1741的那题和类似,求树上节点之间的距离小于等于k的节点对有多少对
解题思路:具体可参考:《分治算法在树的路径问题中的应用——漆子超》
给这题的输入坑了,注意输入,不然会超时
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
#define maxn 40010
int vis[maxn], Sum[maxn], d[maxn], dp[maxn];
int n, k, size, root, m, Ans;
struct node{
int v, l;
node() {}
node(int vv, int ll) {
v = vv;
l = ll;
}
};
vector<node> Node[maxn];
vector<int> dep;
void dfs(int cur, int fa) {
Sum[cur] = 1;
dp[cur] = 0;
for(int i = 0; i < Node[cur].size(); i++) {
if(!vis[Node[cur][i].v] && Node[cur][i].v != fa) {
dfs(Node[cur][i].v, cur);
Sum[cur] += Sum[Node[cur][i].v];
dp[cur] = max(dp[cur], Sum[Node[cur][i].v]);
}
}
dp[cur] = max(dp[cur], size - Sum[cur]);
if(dp[cur] < dp[root])
root = cur;
}
void init() {
for(int i = 1; i <= n; i++) {
Node[i].clear();
vis[i] = 0;
}
int x, y, z;
char c;
for(int i = 0; i < m; i++) {
scanf("%d%d%d %c", &x, &y, &z, &c);
Node[x].push_back(node(y,z));
Node[y].push_back(node(x,z));
}
scanf("%d", &k);
dp[0] = size = n;
Ans = root = 0;
}
void getdep(int cur, int fa) {
dep.push_back(d[cur]);
for(int i = 0; i < Node[cur].size(); i++)
if(!vis[Node[cur][i].v] && Node[cur][i].v != fa) {
d[Node[cur][i].v] = d[cur] + Node[cur][i].l;
getdep(Node[cur][i].v, cur);
}
}
int calc(int cur, int Num) {
dep.clear();
d[cur] = Num;
getdep(cur, 0);
sort(dep.begin(), dep.end());
int cnt = 0;
for(int l = 0, r = dep.size() - 1; l < r; )
if(dep[l] + dep[r] <= k)
cnt += r - l++;
else
r--;
return cnt;
}
void solve(int cur) {
Ans += calc(cur, 0);
vis[cur] = 1;
for(int i = 0; i < Node[cur].size(); i++) {
if(!vis[Node[cur][i].v]) {
Ans -= calc(Node[cur][i].v, Node[cur][i].l);
dp[0] = size = Sum[Node[cur][i].v];
root = 0;
dfs(Node[cur][i].v, 0);
solve(root);
}
}
}
int main() {
scanf("%d%d", &n, &m);
init();
dfs(1,0);
solve(root);
printf("%d\n", Ans);
return 0;
}