| Tim's Programming Space |
|
|||
| Tim's Programming Space | ||||
|
日歷
統計
導航常用鏈接留言簿(3)隨筆檔案文章檔案搜索最新評論
|
1
#include <iostream>2 #include <cstdio>3 #include <cstdlib>4 #include <cstring>5 #include <algorithm>6 ![]() 7 #define MAXN 100008 #define MAXM MAXN*29 ![]() 10 using namespace std;11 ![]() 12 int n,K;13 int Count = 0;14 int begin[MAXN+1],end[MAXM+1],next[MAXM+1],cost[MAXM+1];15 ![]() void AddEdge(int a,int b,int c) {16 Count++;17 next[Count] = begin[a];18 begin[a] = Count;19 end[Count] = b;20 cost[Count] = c;21 }22 void Solve();23 ![]() void Init() {24 ![]() while (true) {25 scanf("%d%d",&n,&K);26 if (n == 0 && K == 0)27 break;28 else29 Solve();30 }31 }32 ![]() 33 ![]() 34 bool hash[MAXN+1];35 int size[MAXN+1];36 ![]() int GetSize(int x,int fa) {37 size[x] = 1;38 for (int now = begin[x]; now; now = next[now])39 if (!hash[end[now]] && end[now]!=fa)40 size[x] += GetSize(end[now],x);41 return size[x];42 }43 ![]() 44 ![]() int GetBestRoot(int x) {45 GetSize(x,0);46 ![]() while (true) {47 int MaxSize = 0,id = 0;48 for (int now = begin[x]; now; now = next[now])49 if (!hash[end[now]] && MaxSize < size[end[now]])50 MaxSize = size[id = end[now]];51 if (MaxSize <= (size[x] >> 1))52 break;53 size[x] -= size[id], size[id] += size[x], x = id;54 }55 return x;56 }57 int dist[MAXN+1];58 int cnt;59 ![]() void GetDist(int x,int fa,int d) {60 if (d>K) return;61 dist[++cnt] = d;62 for (int now = begin[x]; now; now = next[now])63 if (!hash[end[now]] && end[now] != fa)64 GetDist(end[now],x,d + cost[now]);65 }66 ![]() int cmp(const void *a,const void *b) {67 return (*(int *)a) - (*(int *)b);68 }69 ![]() int dfs(int x) {70 x = GetBestRoot(x);71 hash[x] = true;72 int ret = 0;73 for (int now = begin[x]; now; now = next[now])74 if (!hash[end[now]])75 ret += dfs(end[now]);76 cnt = 0;77 GetDist(x,0,0);78 qsort(dist+1,cnt,sizeof(dist[0]),cmp);79 80 81 int l = 1, r = cnt;82 ![]() while (l<r) {83 if (dist[l] + dist[r]<=K) ret += r-l, l++;84 else r--;85 }86 for (int now = begin[x]; now; now = next[now])87 ![]() if (!hash[end[now]]) {88 int limit = K - cost[now] * 2;89 cnt = 0;90 GetDist(end[now],0, 0);91 qsort(dist+1,cnt,sizeof(dist[0]),cmp);92 int l = 1, r = cnt;93 ![]() while (l<r) {94 if (dist[l] + dist[r]<=limit) ret -= r-l, l++;95 else r--;96 }97 }98 hash[x] = false;99 return ret;100 }101 ![]() 102 ![]() void Solve() {103 Count = 0;104 memset(begin,0,sizeof(begin));105 int t1,t2,t3;106 ![]() for (int i = 1; i<n; i++) {107 scanf("%d%d%d",&t1,&t2,&t3);108 AddEdge(t1,t2,t3);109 AddEdge(t2,t1,t3);110 }111 printf("%d\n",dfs(1));112 }113 ![]() 114 ![]() int main() {115 Init();116 return 0;117 }118 ![]() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
![]() |
|
| Copyright © TimTopCoder | Powered by: 博客園 模板提供:滬江博客 |