#include <algorithm> #include <map> #include <vector> #include <unordered_map> #include <set> #include <string.h> #include <stack> #define LL long long #define BIGMOD 1000000007LL #define DNUM 31LL #define MAXN 25002 #define MAX_LEVEL 28 #define K3DBG(X) using namespace std; string to_binary(int x, int n) { string res = ""; while (n > 0) { res += (x & 1) + '0'; x >>=1; n--; } reverse(res.begin(), res.end()); return res; } class BitSet { public: // each 16-bit is a new 'digit' unsigned short data[1600]; BitSet() { clear(); } void clear() { memset(data, 0, sizeof(short) * 1600); } void setbit(int idx) { data[idx >> 4] |= (1 << (idx & 0xF)); } char getbit(int idx) { return (data[idx >> 4] >> (idx & 0xF)) & 1U; } void addbit(int idx) { short si = idx >> 16; unsigned short *digit = &data[si]; bool msbWasSet = ((*digit >> 15) & 1U); *digit += (1 << (idx & 0xF)); if (!msbWasSet) return ; bool msbCleared = msbWasSet && (((*digit >> 15) & 1U) == 0); while (msbCleared) { ++si; digit = &data[si]; msbWasSet = ((*digit >> 15) & 1U); (*digit)++; msbCleared = msbWasSet && (((*digit >> 15) & 1U) == 0); } } void print_digit(int digitIdx, bool newline) { printf("%s", to_binary(data[digitIdx], 16).c_str()); if (newline) { printf("\n"); } } void print(int digits, bool newline) { for (int i=digits-1; i>=0; --i) { print_digit(i, false); printf(" "); } if (newline) { printf("\n"); } } }; class ReversibleBitSet : public BitSet { public: stack<short> lastSetBitData; void reversible_setbit(int idx) { //printf("reversible_setbit %u\n", idx); lastSetBitData.push(data[idx >> 4]); setbit(idx); } void revert_setbit(int idx) { short prev = lastSetBitData.top(); lastSetBitData.pop(); //printf("revert setbit %u to %u\n", idx, prev); data[idx >> 4] = prev; } }; class LCATree { public: vector <int> tree[MAXN]; int depth[MAXN]; int parent[MAXN][MAX_LEVEL]; LCATree() { memset(parent,-1,sizeof(parent)); } // pre-compute the depth for each node and their // first parent(2^0th parent) // time complexity : O(n) void dfs(int cur, int prev) { depth[cur] = depth[prev] + 1; parent[cur][0] = prev; for (int i=0; i<tree[cur].size(); i++) { if (tree[cur][i] != prev) dfs(tree[cur][i], cur); } } // Dynamic Programming Sparse Matrix Approach // populating 2^i parent for each node // Time complexity : O(nlogn) void precomputeSparseMatrix(int n) { for (int i=1; i<MAX_LEVEL; i++) { for (int node = 1; node <= n; node++) { if (parent[node][i-1] != -1) parent[node][i] = parent[parent[node][i-1]][i-1]; } } } // Returning the LCA of u and v // Time complexity : O(log n) int lca(int u, int v) { if (depth[v] < depth[u]) swap(u, v); int diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (int i=0; i<MAX_LEVEL; i++) if ((diff>>i)&1) v = parent[v][i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (int i=MAX_LEVEL-1; i>=0; i--) if (parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } return parent[u][0]; } void addEdge(int u,int v) { tree[u].push_back(v); tree[v].push_back(u); } void precompute(int n) { dfs(1,0); precomputeSparseMatrix(n); } }; class DirectRoad { public: DirectRoad(int a, int b, int pi) : from(a), to(b), pi(pi) {} short from; short to; short pi; }; class ShortRoad { public: ShortRoad(int from, int to) : from(from), to(to) {} short from; short to; void print() { printf("(%u->%u)", from, to); } }; void consolidate(vector<pair<short, short> > &vs) { if (vs.size() == 0) { return; } vector<pair<short, short> > res; vector<pair<short, short> > &tmp = vs; sort(tmp.begin(), tmp.end(), [](const pair<short, short> &lhs, const pair<short, short> rhs){ return lhs > rhs; }); pair<short, short> &prev = tmp[0]; for (int i=1; i < tmp.size(); i++) { pair<short, short> ¤t = tmp[i]; if (current.first == prev.first) { prev.second += current.second; } else { res.push_back(prev); prev = current; } } res.push_back(prev); vs = res; } void print_cost_vec(const vector<pair< short, short> > &vs) { printf("["); for (int i=0; i < vs.size(); i++) { printf("(%dxn^%d)", vs[i].second, vs[i].first); } printf("]"); } class TreeCostFromRoot { public: // ktora potega, ile razy wystapila vector<pair<short, short> > costFromRoot[MAXN]; void addCost(int v, stack<short> cost) { vector<pair<short, short> > tmp; while (!cost.empty()) { tmp.push_back(make_pair(cost.top(), 1)); cost.pop(); } //consolidate(tmp); costFromRoot[v] = tmp; } void consolidate_all(int n) { for (int i=0; i <=n ;i++) { consolidate(costFromRoot[i]); } } void print_cost_to(short v) { vector<pair<short, short> > &vs = costFromRoot[v]; print_cost_vec(vs); } }; void print_stack(const stack<short>& s) { stack<short> cs = s; while (!cs.empty()) { printf("%u ", cs.top()); cs.pop(); } printf("\n"); } BitSet alreadyComputed[MAXN]; // 80MB vector<DirectRoad> tree[MAXN]; // male, bo tylko 'n' krawedzi LCATree lcaTree; // male TreeCostFromRoot costFromRoot; // MAXN * (at worst) MAXN * (2 shorts) // to tez za duze... vector<pair<short, short> > radixData[MAXN]; int radixDataCountOnly[65537] = {0}; int dfs_visited[25010]; int dfs_visited_counter = 0; void treeCostBetweenUandV(const TreeCostFromRoot &tr, short u, short v, vector<pair<short, short> > &res) { //printf("treeCostBetweenUandV (%u,%u)", u, v); const vector<pair<short, short> > &u_vec = tr.costFromRoot[u]; const vector<pair<short, short> > &v_vec = tr.costFromRoot[v]; short lca = lcaTree.lca(u, v); const vector<pair<short, short> > &lca_vec = tr.costFromRoot[lca]; /*printf("u cost: "); print_cost_vec(u_vec); printf(" | "); printf("v cost: "); print_cost_vec(v_vec); printf(" | ");*/ for (int i=0; i < u_vec.size(); i++) { res.push_back(u_vec[i]); } for (int i=0; i < v_vec.size(); i++) { res.push_back(v_vec[i]); } for (int i=0; i < lca_vec.size(); i++) { res.push_back(make_pair(lca_vec[i].first, lca_vec[i].second * -2)); } sort(res.begin(), res.end(), [](const pair<short, short> &lhs, const pair<short, short> rhs){ return lhs > rhs; }); //reverse(res.begin(), res.end()); //print_cost_vec(res); printf(" | "); consolidate(res); //return res; } void clear_already_computed(int n) { for (int i=0; i <= n; i++) { alreadyComputed[i].clear(); } } void dfsRadix(short rootId, short nodeId, short parentId, short maxPi, stack<short> &maxPiSoFarStack, short rememberOnlyXthBucket, int ileMaxPiCount) { const vector<DirectRoad> &v = tree[nodeId]; dfs_visited[nodeId] = dfs_visited_counter; //printf("dfs root:%u node:%u parent:%u\n", rootId, nodeId, parentId); for (int i=0; i < v.size(); i++) { const DirectRoad &peer = v[i]; if (peer.to == parentId) { continue; } if (dfs_visited[peer.to] == dfs_visited_counter) { continue; } short maxFromStack = -1; if (!maxPiSoFarStack.empty()) { maxFromStack = maxPiSoFarStack.top(); } int tmpIleMaxPiCount = ileMaxPiCount; if (peer.pi > maxFromStack) { tmpIleMaxPiCount = 0; } else if (peer.pi == maxFromStack) { tmpIleMaxPiCount = ileMaxPiCount + 1; } short maxPiSoFar = max(peer.pi, maxFromStack); maxPiSoFarStack.push(maxPiSoFar); /*short idx = -1; if (maxPi - peer.pi < 16) { idx = 15 - (maxPi - peer.pi); } rbs.reversible_setbit(idx);*/ short orderedFrom = rootId; short orderedTo = peer.to; if (orderedFrom > orderedTo) swap(orderedFrom, orderedTo); if (!alreadyComputed[orderedFrom].getbit(orderedTo)) { if (rememberOnlyXthBucket == maxPiSoFar) { radixData[tmpIleMaxPiCount].push_back(make_pair(orderedFrom, orderedTo)); } else { radixDataCountOnly[maxPiSoFar]++; } alreadyComputed[orderedFrom].setbit(orderedTo); } // printf("Cost from %u to %u is ", rootId, peer.to); print_stack(costSoFar); dfsRadix(rootId, peer.to, peer.from, maxPi, maxPiSoFarStack, rememberOnlyXthBucket, tmpIleMaxPiCount); maxPiSoFarStack.pop(); //rbs.revert_setbit(idx); } } void dfs(short rootId, short nodeId, short parentId, stack<short> &costSoFar) { const vector<DirectRoad> &v = tree[nodeId]; dfs_visited[nodeId] = dfs_visited_counter; //printf("dfs root:%u node:%u parent:%u\n", rootId, nodeId, parentId); for (int i=0; i < v.size(); i++) { const DirectRoad &peer = v[i]; if (peer.to == parentId) { continue; } if (dfs_visited[peer.to] == dfs_visited_counter) { continue; } costSoFar.push(peer.pi); // printf("Cost from %u to %u is ", rootId, peer.to); print_stack(costSoFar); dfs(rootId, peer.to, peer.from, costSoFar); costFromRoot.addCost(peer.to, costSoFar); costSoFar.pop(); } } void wyznaczDlugosciTrasFromRoot(int numberOfCities) { stack<short> costSoFar; dfs_visited_counter++; dfs(1, 1, -1, costSoFar); costFromRoot.consolidate_all(numberOfCities); } //BitSet costFromRoot[MAXN]; pair<int, int> radixZnajdzIndexKubelka(int k, bool other) { //printf("radixZnajdzIndexKubelka k=%d\n", k); for (int i=0; i < (1 << 16); i++) { //printf("checking kubelek %d...rozmiar: %d\n", i, radixDataCountOnly[i]); int bucketSize = radixDataCountOnly[i]; if (other) { bucketSize = radixData[i].size(); } if (k <= bucketSize) { //printf("returning i,k=(%d,%d) bs=%d", i, k,bucketSize); return make_pair(i, k); } k -= bucketSize; } //printf("oops\n"); return make_pair(0,0); } void radixWypiszTrasy() { for (int i=0; i < MAXN; i++) { if (radixData[i].size() > 0) { printf("trasy o dlugosci %d ", i);printf("%s ", to_binary(i, 8).c_str()); for (int j=0; j < radixData[i].size(); j++) { printf("(%d->%d)",radixData[i][j].first, radixData[i][j].second); } printf("\n"); } } } pair<int, int> radixWyznaczDlugosciTras(int maxPi, int numberOfCities, int k) { ReversibleBitSet bitset; for (int i=0; i < 65536; i++) { radixDataCountOnly[i] = 0; } clear_already_computed(numberOfCities); for (int i=1; i <= numberOfCities; i++) { stack<short> maxPiSoFarStack; //printf("new dfs:"); //bitset.clear(); dfs_visited_counter++; dfsRadix(i, i, -1, maxPi, maxPiSoFarStack, -1, 0); } radixWypiszTrasy(); pair<int, int> pr = radixZnajdzIndexKubelka(k, false); int newK = pr.second; clear_already_computed(numberOfCities); for (int i=0; i <= 65536; i++) { radixDataCountOnly[i] = 0; } for (int i=1; i <= numberOfCities; i++) { stack<short> maxPiSoFarStack; //printf("new dfs:"); //bitset.clear(); dfs_visited_counter++; dfsRadix(i, i, -1, maxPi, maxPiSoFarStack, pr.first, 0); } pr = radixZnajdzIndexKubelka(newK, true); return pr; } void printAllCosts(int n) { for (int i=1; i < n; i++) { for (int j=i+1; j <=n; j++) { printf("cost from %u->%u is ", i, j); costFromRoot.print_cost_to(i); printf("+"); costFromRoot.print_cost_to(j); short lca = lcaTree.lca(i, j); printf("-2*lca=%u ", lca); costFromRoot.print_cost_to(lca); printf(" res="); vector<pair<short, short> > res; treeCostBetweenUandV(costFromRoot, i, j, res); print_cost_vec(res); printf("\n"); } } } void selftest() { /*printf("%s\n", to_binary(7, 5).c_str()); ReversibleBitSet bs; bs.setbit(2); bs.setbit(3); printf("bit 5 = %d\n", bs.getbit(5)); bs.setbit(5); printf("bit 5 = %d\n", bs.getbit(5)); bs.data[0] = 0xFFF0; bs.data[1] = 0xFFFF; bs.data[2] = 0x2; bs.print(3, true); bs.reversible_addbit(5); bs.print(3, true); bs.revert_addbit(); bs.print(3, true);*/ } void generate_all_pairs(int n, vector<pair<short, short> > &res) { for (int i=1; i < n; i++) { for (int j=i+1; j <=n; j++) { res.push_back(make_pair(i,j)); } } } short compareDistanceByVector(vector<pair<short, short> > &v1, vector<pair<short, short> > v2) { int i =0; int j = 0; //printf("compareDistanceByVector: "); // print_cost_vec(v1); printf(" | "); print_cost_vec(v2); while (i < v1.size() && j < v2.size()) { pair<short, short> p1 = v1[i]; pair<short, short> p2 = v2[j]; //printf("comparing pairs: (%d,%d) vs. (%d,%d)\n", p1.first, p1.second, p2.first, p2.second); if (p1.second == 0) { i++; continue; } if (p2.second == 0) { j++; continue; } if (p1.first < p2.first) { return -1; } else if (p1.first > p2.first) { return 1; } else { if (p1.second < p2.second) { return -1; } else if (p1.second > p2.second) { return 1; } } i++; j++; } if (i == v1.size() && j == v2.size()) { return 0; } if (i < v1.size()) return 1; return -1; } bool compareDistanceByPair(pair<short, short> p1, pair<short, short> p2) { vector<pair<short, short> > cost1; vector<pair<short, short> > cost2; treeCostBetweenUandV(costFromRoot, p1.first, p1.second, cost1); treeCostBetweenUandV(costFromRoot, p2.first, p2.second, cost2); // jesli -1, to cost1 < cost2 int res = compareDistanceByVector(cost1, cost2); // printf("compare (%d,%d) with (%d,%d) res = %d\n", p1.first, p1.second, p2.first, p2.second, res); return res == -1; } /* Iterative Function to calculate (x^y)%p in O(log y) */ LL powmod(LL x, unsigned int y, LL p) { LL res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res; } LL calculateMod(int n, pair<short, short> fromUtoV) { LL res = 0; //printf("calculate mod: (%d,%d)", fromUtoV.first, fromUtoV.second); vector<pair<short, short> > cost1; treeCostBetweenUandV(costFromRoot, fromUtoV.first, fromUtoV.second, cost1); //print_cost_vec(cost1); for (int i=0; i < cost1.size(); i++) { if (cost1[i].second == 0) continue; LL m = powmod(n, cost1[i].first, BIGMOD); m *= (LL)cost1[i].second; m %= BIGMOD; res += m; } return res % BIGMOD; } int main() { //selftest(); int n,k; scanf("%d%d", &n, &k); int maxPi = 15; for (int i=0; i < n-1; i++) { int a,b,pi; scanf("%d%d%d", &a, &b, &pi); tree[a].push_back(DirectRoad(a,b,pi)); tree[b].push_back(DirectRoad(b,a,pi)); lcaTree.addEdge(a,b); maxPi = max(pi, maxPi); } lcaTree.precompute(n); //printf("lca(1,2) %d\n", lcaTree.lca(1,2)); //printf("lca(4,2) %d\n", lcaTree.lca(5,2)); pair<int, int> bucketAndNewK = radixWyznaczDlugosciTras(maxPi, n, k); //radixWypiszTrasy(); wyznaczDlugosciTrasFromRoot(n); //printAllCosts(n); //pair<int, int> bucketAndNewK = radixZnajdzIndexKubelka(k); //printf("looking only in kubelek %d for k=%d (rozmiaru: %d)\n", bucketAndNewK.first, bucketAndNewK.second, radixData[bucketAndNewK.first].size()); k = bucketAndNewK.second; auto &all_pairs = radixData[bucketAndNewK.first]; //vector<pair<short, short> > all_pairs; //generate_all_pairs(n, all_pairs); //clear_already_computed(n); std::sort(all_pairs.begin(), all_pairs.end(), compareDistanceByPair); for (int i=0; i < all_pairs.size(); i++) { /*printf("idx=%d (%d,%d)", i, all_pairs[i].first, all_pairs[i].second); vector<pair<short, short> > cost; treeCostBetweenUandV(costFromRoot, all_pairs[i].first, all_pairs[i].second, cost); print_cost_vec(cost); printf("res=%lld\n", calculateMod(n, all_pairs[i]));*/ } printf("%lld", calculateMod(n, all_pairs[k-1])); //auto vs = treeCostBetweenUandV(costFromRoot, 4, 9); } /* idx=10 (6,8)[(2xn^3)(0xn^1)]res=2000 idx=11 (4,7)[(2xn^3)(1xn^1)]res=2010 idx=12 (3,7)[(2xn^3)(2xn^1)]res=2020 idx=13 (2,7)[(2xn^3)(3xn^1)]res=2030 idx=14 (1,7)[(2xn^3)(4xn^1)]res=2040 idx=15 (6,9)[(2xn^3)(1xn^2)(0xn^1)]res=2100 idx=16 (6,10)[(2xn^3)(2xn^2)(0xn^1)]res=2200 */
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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 | #include <algorithm> #include <map> #include <vector> #include <unordered_map> #include <set> #include <string.h> #include <stack> #define LL long long #define BIGMOD 1000000007LL #define DNUM 31LL #define MAXN 25002 #define MAX_LEVEL 28 #define K3DBG(X) using namespace std; string to_binary(int x, int n) { string res = ""; while (n > 0) { res += (x & 1) + '0'; x >>=1; n--; } reverse(res.begin(), res.end()); return res; } class BitSet { public: // each 16-bit is a new 'digit' unsigned short data[1600]; BitSet() { clear(); } void clear() { memset(data, 0, sizeof(short) * 1600); } void setbit(int idx) { data[idx >> 4] |= (1 << (idx & 0xF)); } char getbit(int idx) { return (data[idx >> 4] >> (idx & 0xF)) & 1U; } void addbit(int idx) { short si = idx >> 16; unsigned short *digit = &data[si]; bool msbWasSet = ((*digit >> 15) & 1U); *digit += (1 << (idx & 0xF)); if (!msbWasSet) return ; bool msbCleared = msbWasSet && (((*digit >> 15) & 1U) == 0); while (msbCleared) { ++si; digit = &data[si]; msbWasSet = ((*digit >> 15) & 1U); (*digit)++; msbCleared = msbWasSet && (((*digit >> 15) & 1U) == 0); } } void print_digit(int digitIdx, bool newline) { printf("%s", to_binary(data[digitIdx], 16).c_str()); if (newline) { printf("\n"); } } void print(int digits, bool newline) { for (int i=digits-1; i>=0; --i) { print_digit(i, false); printf(" "); } if (newline) { printf("\n"); } } }; class ReversibleBitSet : public BitSet { public: stack<short> lastSetBitData; void reversible_setbit(int idx) { //printf("reversible_setbit %u\n", idx); lastSetBitData.push(data[idx >> 4]); setbit(idx); } void revert_setbit(int idx) { short prev = lastSetBitData.top(); lastSetBitData.pop(); //printf("revert setbit %u to %u\n", idx, prev); data[idx >> 4] = prev; } }; class LCATree { public: vector <int> tree[MAXN]; int depth[MAXN]; int parent[MAXN][MAX_LEVEL]; LCATree() { memset(parent,-1,sizeof(parent)); } // pre-compute the depth for each node and their // first parent(2^0th parent) // time complexity : O(n) void dfs(int cur, int prev) { depth[cur] = depth[prev] + 1; parent[cur][0] = prev; for (int i=0; i<tree[cur].size(); i++) { if (tree[cur][i] != prev) dfs(tree[cur][i], cur); } } // Dynamic Programming Sparse Matrix Approach // populating 2^i parent for each node // Time complexity : O(nlogn) void precomputeSparseMatrix(int n) { for (int i=1; i<MAX_LEVEL; i++) { for (int node = 1; node <= n; node++) { if (parent[node][i-1] != -1) parent[node][i] = parent[parent[node][i-1]][i-1]; } } } // Returning the LCA of u and v // Time complexity : O(log n) int lca(int u, int v) { if (depth[v] < depth[u]) swap(u, v); int diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (int i=0; i<MAX_LEVEL; i++) if ((diff>>i)&1) v = parent[v][i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (int i=MAX_LEVEL-1; i>=0; i--) if (parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } return parent[u][0]; } void addEdge(int u,int v) { tree[u].push_back(v); tree[v].push_back(u); } void precompute(int n) { dfs(1,0); precomputeSparseMatrix(n); } }; class DirectRoad { public: DirectRoad(int a, int b, int pi) : from(a), to(b), pi(pi) {} short from; short to; short pi; }; class ShortRoad { public: ShortRoad(int from, int to) : from(from), to(to) {} short from; short to; void print() { printf("(%u->%u)", from, to); } }; void consolidate(vector<pair<short, short> > &vs) { if (vs.size() == 0) { return; } vector<pair<short, short> > res; vector<pair<short, short> > &tmp = vs; sort(tmp.begin(), tmp.end(), [](const pair<short, short> &lhs, const pair<short, short> rhs){ return lhs > rhs; }); pair<short, short> &prev = tmp[0]; for (int i=1; i < tmp.size(); i++) { pair<short, short> ¤t = tmp[i]; if (current.first == prev.first) { prev.second += current.second; } else { res.push_back(prev); prev = current; } } res.push_back(prev); vs = res; } void print_cost_vec(const vector<pair< short, short> > &vs) { printf("["); for (int i=0; i < vs.size(); i++) { printf("(%dxn^%d)", vs[i].second, vs[i].first); } printf("]"); } class TreeCostFromRoot { public: // ktora potega, ile razy wystapila vector<pair<short, short> > costFromRoot[MAXN]; void addCost(int v, stack<short> cost) { vector<pair<short, short> > tmp; while (!cost.empty()) { tmp.push_back(make_pair(cost.top(), 1)); cost.pop(); } //consolidate(tmp); costFromRoot[v] = tmp; } void consolidate_all(int n) { for (int i=0; i <=n ;i++) { consolidate(costFromRoot[i]); } } void print_cost_to(short v) { vector<pair<short, short> > &vs = costFromRoot[v]; print_cost_vec(vs); } }; void print_stack(const stack<short>& s) { stack<short> cs = s; while (!cs.empty()) { printf("%u ", cs.top()); cs.pop(); } printf("\n"); } BitSet alreadyComputed[MAXN]; // 80MB vector<DirectRoad> tree[MAXN]; // male, bo tylko 'n' krawedzi LCATree lcaTree; // male TreeCostFromRoot costFromRoot; // MAXN * (at worst) MAXN * (2 shorts) // to tez za duze... vector<pair<short, short> > radixData[MAXN]; int radixDataCountOnly[65537] = {0}; int dfs_visited[25010]; int dfs_visited_counter = 0; void treeCostBetweenUandV(const TreeCostFromRoot &tr, short u, short v, vector<pair<short, short> > &res) { //printf("treeCostBetweenUandV (%u,%u)", u, v); const vector<pair<short, short> > &u_vec = tr.costFromRoot[u]; const vector<pair<short, short> > &v_vec = tr.costFromRoot[v]; short lca = lcaTree.lca(u, v); const vector<pair<short, short> > &lca_vec = tr.costFromRoot[lca]; /*printf("u cost: "); print_cost_vec(u_vec); printf(" | "); printf("v cost: "); print_cost_vec(v_vec); printf(" | ");*/ for (int i=0; i < u_vec.size(); i++) { res.push_back(u_vec[i]); } for (int i=0; i < v_vec.size(); i++) { res.push_back(v_vec[i]); } for (int i=0; i < lca_vec.size(); i++) { res.push_back(make_pair(lca_vec[i].first, lca_vec[i].second * -2)); } sort(res.begin(), res.end(), [](const pair<short, short> &lhs, const pair<short, short> rhs){ return lhs > rhs; }); //reverse(res.begin(), res.end()); //print_cost_vec(res); printf(" | "); consolidate(res); //return res; } void clear_already_computed(int n) { for (int i=0; i <= n; i++) { alreadyComputed[i].clear(); } } void dfsRadix(short rootId, short nodeId, short parentId, short maxPi, stack<short> &maxPiSoFarStack, short rememberOnlyXthBucket, int ileMaxPiCount) { const vector<DirectRoad> &v = tree[nodeId]; dfs_visited[nodeId] = dfs_visited_counter; //printf("dfs root:%u node:%u parent:%u\n", rootId, nodeId, parentId); for (int i=0; i < v.size(); i++) { const DirectRoad &peer = v[i]; if (peer.to == parentId) { continue; } if (dfs_visited[peer.to] == dfs_visited_counter) { continue; } short maxFromStack = -1; if (!maxPiSoFarStack.empty()) { maxFromStack = maxPiSoFarStack.top(); } int tmpIleMaxPiCount = ileMaxPiCount; if (peer.pi > maxFromStack) { tmpIleMaxPiCount = 0; } else if (peer.pi == maxFromStack) { tmpIleMaxPiCount = ileMaxPiCount + 1; } short maxPiSoFar = max(peer.pi, maxFromStack); maxPiSoFarStack.push(maxPiSoFar); /*short idx = -1; if (maxPi - peer.pi < 16) { idx = 15 - (maxPi - peer.pi); } rbs.reversible_setbit(idx);*/ short orderedFrom = rootId; short orderedTo = peer.to; if (orderedFrom > orderedTo) swap(orderedFrom, orderedTo); if (!alreadyComputed[orderedFrom].getbit(orderedTo)) { if (rememberOnlyXthBucket == maxPiSoFar) { radixData[tmpIleMaxPiCount].push_back(make_pair(orderedFrom, orderedTo)); } else { radixDataCountOnly[maxPiSoFar]++; } alreadyComputed[orderedFrom].setbit(orderedTo); } // printf("Cost from %u to %u is ", rootId, peer.to); print_stack(costSoFar); dfsRadix(rootId, peer.to, peer.from, maxPi, maxPiSoFarStack, rememberOnlyXthBucket, tmpIleMaxPiCount); maxPiSoFarStack.pop(); //rbs.revert_setbit(idx); } } void dfs(short rootId, short nodeId, short parentId, stack<short> &costSoFar) { const vector<DirectRoad> &v = tree[nodeId]; dfs_visited[nodeId] = dfs_visited_counter; //printf("dfs root:%u node:%u parent:%u\n", rootId, nodeId, parentId); for (int i=0; i < v.size(); i++) { const DirectRoad &peer = v[i]; if (peer.to == parentId) { continue; } if (dfs_visited[peer.to] == dfs_visited_counter) { continue; } costSoFar.push(peer.pi); // printf("Cost from %u to %u is ", rootId, peer.to); print_stack(costSoFar); dfs(rootId, peer.to, peer.from, costSoFar); costFromRoot.addCost(peer.to, costSoFar); costSoFar.pop(); } } void wyznaczDlugosciTrasFromRoot(int numberOfCities) { stack<short> costSoFar; dfs_visited_counter++; dfs(1, 1, -1, costSoFar); costFromRoot.consolidate_all(numberOfCities); } //BitSet costFromRoot[MAXN]; pair<int, int> radixZnajdzIndexKubelka(int k, bool other) { //printf("radixZnajdzIndexKubelka k=%d\n", k); for (int i=0; i < (1 << 16); i++) { //printf("checking kubelek %d...rozmiar: %d\n", i, radixDataCountOnly[i]); int bucketSize = radixDataCountOnly[i]; if (other) { bucketSize = radixData[i].size(); } if (k <= bucketSize) { //printf("returning i,k=(%d,%d) bs=%d", i, k,bucketSize); return make_pair(i, k); } k -= bucketSize; } //printf("oops\n"); return make_pair(0,0); } void radixWypiszTrasy() { for (int i=0; i < MAXN; i++) { if (radixData[i].size() > 0) { printf("trasy o dlugosci %d ", i);printf("%s ", to_binary(i, 8).c_str()); for (int j=0; j < radixData[i].size(); j++) { printf("(%d->%d)",radixData[i][j].first, radixData[i][j].second); } printf("\n"); } } } pair<int, int> radixWyznaczDlugosciTras(int maxPi, int numberOfCities, int k) { ReversibleBitSet bitset; for (int i=0; i < 65536; i++) { radixDataCountOnly[i] = 0; } clear_already_computed(numberOfCities); for (int i=1; i <= numberOfCities; i++) { stack<short> maxPiSoFarStack; //printf("new dfs:"); //bitset.clear(); dfs_visited_counter++; dfsRadix(i, i, -1, maxPi, maxPiSoFarStack, -1, 0); } radixWypiszTrasy(); pair<int, int> pr = radixZnajdzIndexKubelka(k, false); int newK = pr.second; clear_already_computed(numberOfCities); for (int i=0; i <= 65536; i++) { radixDataCountOnly[i] = 0; } for (int i=1; i <= numberOfCities; i++) { stack<short> maxPiSoFarStack; //printf("new dfs:"); //bitset.clear(); dfs_visited_counter++; dfsRadix(i, i, -1, maxPi, maxPiSoFarStack, pr.first, 0); } pr = radixZnajdzIndexKubelka(newK, true); return pr; } void printAllCosts(int n) { for (int i=1; i < n; i++) { for (int j=i+1; j <=n; j++) { printf("cost from %u->%u is ", i, j); costFromRoot.print_cost_to(i); printf("+"); costFromRoot.print_cost_to(j); short lca = lcaTree.lca(i, j); printf("-2*lca=%u ", lca); costFromRoot.print_cost_to(lca); printf(" res="); vector<pair<short, short> > res; treeCostBetweenUandV(costFromRoot, i, j, res); print_cost_vec(res); printf("\n"); } } } void selftest() { /*printf("%s\n", to_binary(7, 5).c_str()); ReversibleBitSet bs; bs.setbit(2); bs.setbit(3); printf("bit 5 = %d\n", bs.getbit(5)); bs.setbit(5); printf("bit 5 = %d\n", bs.getbit(5)); bs.data[0] = 0xFFF0; bs.data[1] = 0xFFFF; bs.data[2] = 0x2; bs.print(3, true); bs.reversible_addbit(5); bs.print(3, true); bs.revert_addbit(); bs.print(3, true);*/ } void generate_all_pairs(int n, vector<pair<short, short> > &res) { for (int i=1; i < n; i++) { for (int j=i+1; j <=n; j++) { res.push_back(make_pair(i,j)); } } } short compareDistanceByVector(vector<pair<short, short> > &v1, vector<pair<short, short> > v2) { int i =0; int j = 0; //printf("compareDistanceByVector: "); // print_cost_vec(v1); printf(" | "); print_cost_vec(v2); while (i < v1.size() && j < v2.size()) { pair<short, short> p1 = v1[i]; pair<short, short> p2 = v2[j]; //printf("comparing pairs: (%d,%d) vs. (%d,%d)\n", p1.first, p1.second, p2.first, p2.second); if (p1.second == 0) { i++; continue; } if (p2.second == 0) { j++; continue; } if (p1.first < p2.first) { return -1; } else if (p1.first > p2.first) { return 1; } else { if (p1.second < p2.second) { return -1; } else if (p1.second > p2.second) { return 1; } } i++; j++; } if (i == v1.size() && j == v2.size()) { return 0; } if (i < v1.size()) return 1; return -1; } bool compareDistanceByPair(pair<short, short> p1, pair<short, short> p2) { vector<pair<short, short> > cost1; vector<pair<short, short> > cost2; treeCostBetweenUandV(costFromRoot, p1.first, p1.second, cost1); treeCostBetweenUandV(costFromRoot, p2.first, p2.second, cost2); // jesli -1, to cost1 < cost2 int res = compareDistanceByVector(cost1, cost2); // printf("compare (%d,%d) with (%d,%d) res = %d\n", p1.first, p1.second, p2.first, p2.second, res); return res == -1; } /* Iterative Function to calculate (x^y)%p in O(log y) */ LL powmod(LL x, unsigned int y, LL p) { LL res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res; } LL calculateMod(int n, pair<short, short> fromUtoV) { LL res = 0; //printf("calculate mod: (%d,%d)", fromUtoV.first, fromUtoV.second); vector<pair<short, short> > cost1; treeCostBetweenUandV(costFromRoot, fromUtoV.first, fromUtoV.second, cost1); //print_cost_vec(cost1); for (int i=0; i < cost1.size(); i++) { if (cost1[i].second == 0) continue; LL m = powmod(n, cost1[i].first, BIGMOD); m *= (LL)cost1[i].second; m %= BIGMOD; res += m; } return res % BIGMOD; } int main() { //selftest(); int n,k; scanf("%d%d", &n, &k); int maxPi = 15; for (int i=0; i < n-1; i++) { int a,b,pi; scanf("%d%d%d", &a, &b, &pi); tree[a].push_back(DirectRoad(a,b,pi)); tree[b].push_back(DirectRoad(b,a,pi)); lcaTree.addEdge(a,b); maxPi = max(pi, maxPi); } lcaTree.precompute(n); //printf("lca(1,2) %d\n", lcaTree.lca(1,2)); //printf("lca(4,2) %d\n", lcaTree.lca(5,2)); pair<int, int> bucketAndNewK = radixWyznaczDlugosciTras(maxPi, n, k); //radixWypiszTrasy(); wyznaczDlugosciTrasFromRoot(n); //printAllCosts(n); //pair<int, int> bucketAndNewK = radixZnajdzIndexKubelka(k); //printf("looking only in kubelek %d for k=%d (rozmiaru: %d)\n", bucketAndNewK.first, bucketAndNewK.second, radixData[bucketAndNewK.first].size()); k = bucketAndNewK.second; auto &all_pairs = radixData[bucketAndNewK.first]; //vector<pair<short, short> > all_pairs; //generate_all_pairs(n, all_pairs); //clear_already_computed(n); std::sort(all_pairs.begin(), all_pairs.end(), compareDistanceByPair); for (int i=0; i < all_pairs.size(); i++) { /*printf("idx=%d (%d,%d)", i, all_pairs[i].first, all_pairs[i].second); vector<pair<short, short> > cost; treeCostBetweenUandV(costFromRoot, all_pairs[i].first, all_pairs[i].second, cost); print_cost_vec(cost); printf("res=%lld\n", calculateMod(n, all_pairs[i]));*/ } printf("%lld", calculateMod(n, all_pairs[k-1])); //auto vs = treeCostBetweenUandV(costFromRoot, 4, 9); } /* idx=10 (6,8)[(2xn^3)(0xn^1)]res=2000 idx=11 (4,7)[(2xn^3)(1xn^1)]res=2010 idx=12 (3,7)[(2xn^3)(2xn^1)]res=2020 idx=13 (2,7)[(2xn^3)(3xn^1)]res=2030 idx=14 (1,7)[(2xn^3)(4xn^1)]res=2040 idx=15 (6,9)[(2xn^3)(1xn^2)(0xn^1)]res=2100 idx=16 (6,10)[(2xn^3)(2xn^2)(0xn^1)]res=2200 */ |