1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <queue> #include <set> #define MAXN 200005 #define p 1000000007 #define LL long long using namespace std;
int T, n, k, cnt, head[MAXN]; LL ans[MAXN], inv[MAXN];
struct Edge {int next, to, dis;} edge[MAXN]; struct Node { LL x, y; bool friend operator < (Node a, Node b) { return a.y*b.x<b.y*a.x; } } node[MAXN];
multiset<Node> st; multiset<Node>::iterator it;
void addedge(int from, int to, int dis) { edge[++cnt].next=head[from]; edge[cnt].to=to; edge[cnt].dis=dis; head[from]=cnt; }
void dfs(int x, LL val) { int maxd=-1; for(int i=head[x]; i; i=edge[i].next) maxd=max(maxd, edge[i].dis); if(maxd==-1) ans[x]=val; for(int i=head[x]; i; i=edge[i].next) { node[i].x=edge[i].dis; node[i].y=maxd; Node top= *st.begin(); LL tag=0, temp=val; if(st.size()<k) { tag=1; st.insert(node[i]); temp=temp*inv[200000]%p*node[i].y%p; } else if(top<node[i]) { tag=2; st.erase(st.begin()); st.insert(node[i]); temp=temp*inv[top.y]%p*top.x%p; temp=temp*inv[200000]%p*node[i].y%p; } else temp=temp*inv[200000]%p*node[i].x%p; dfs(edge[i].to, temp); if(tag==1) { it=st.lower_bound(node[i]); st.erase(it); } if(tag==2) { it=st.lower_bound(node[i]); st.erase(it); st.insert(top); } } }
int main() { inv[0]=inv[1]=1; for(int i=2; i<=200000; i++) inv[i]=inv[p%i]*(p-p/i)%p; scanf("%d", &T); while(T--) { cnt=0; memset(head, 0, sizeof(head)); memset(ans, -1, sizeof(ans)); scanf("%d%d", &n, &k); for(int i=1; i<n; i++) { int x, y, z; scanf("%d%d%d", &x, &y, &z); x++, y++; addedge(x, y, z); } dfs(1, 1); for(int i=1; i<=n; i++) if(ans[i]!=-1) printf("%lld\n", ans[i]); } }
|