题意:给定一棵树,然后给定每条边的权值,问你有多少个点对满足路径的权和小于等于m。
析:直接枚举是肯定不行的,会TLE,利用分治的思想,我们可以把树按重心分成几部分,那么答案就是所有子树的点对都经过重心的,对于所有的子树的重心也是这样,对于经过重心的,可以先求出每个点都重心的距离,再排序,利用单调性进行计算,这样的话会算重了,多算了在同一棵子树上的情况,这样再减去就好了。时间复杂度O(n*logn*logn)。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const LL LNF = 1e16; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 1e4 + 10; const int mod = 1e9 + 7; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } vector<P> G[maxn]; int sz[maxn], f[maxn]; int root, num, ans; int d[maxn]; bool vis[maxn]; vector<int> dist; void dfs_for_root(int u, int fa){ sz[u] = 1; f[u] = 0; for(int i = 0; i < G[u].size(); ++i){ int v = G[u][i].first; if(v == fa || vis[v]) continue; dfs_for_root(v, u); sz[u] += sz[v]; f[u] = max(f[u], sz[v]); } f[u] = max(f[u], num - sz[u]); if(f[u] < f[root]) root = u; } void dfs_for_dist(int u, int fa){ dist.push_back(d[u]); for(int i = 0; i < G[u].size(); ++i){ int v = G[u][i].first; if(v == fa || vis[v]) continue; d[v] = d[u] + G[u][i].second; dfs_for_dist(v, u); } } int solve(int u, int val){ dist.clear(); int res = 0; d[u] = val; dfs_for_dist(u, -1); sort(dist.begin(), dist.end()); for(int l = 0, r = (int)dist.size()-1; l < r; ) if(dist[l] + dist[r] <= m) res += r - l++; else --r; return res; } void dfs_for_ans(int u){ ans += solve(u, 0); vis[u] = true; for(int i = 0; i < G[u].size(); ++i){ int v = G[u][i].first; if(vis[v]) continue; ans -= solve(v, G[u][i].second); root = 0; f[0] = num = sz[v]; dfs_for_root(v, u); dfs_for_ans(root); } } int main(){ while(scanf("%d %d", &n, &m) == 2 && n+m){ for(int i = 1; i <= n; ++i) G[i].clear(); for(int i = 1; i < n; ++i){ int u, v, l; scanf("%d %d %d", &u, &v, &l); G[u].push_back(P(v, l)); G[v].push_back(P(u, l)); } f[0] = num = n; root = 0; memset(vis, 0, sizeof vis); dfs_for_root(1, root); ans = 0; dfs_for_ans(root); printf("%d\n", ans); } return 0; }