CodeForces-724G.cpp 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. using ull = unsigned long long;
  4. constexpr long long MOD = 1'000'000'007LL;
  5. constexpr int BITS = 60;
  6. struct LinearBasis {
  7. array<ull, BITS> pivot{};
  8. int rank = 0;
  9. void insert(ull value) {
  10. for (int bit = BITS - 1; bit >= 0; --bit) {
  11. if (((value >> bit) & 1ULL) == 0) continue;
  12. if (pivot[bit] == 0) {
  13. pivot[bit] = value;
  14. ++rank;
  15. return;
  16. }
  17. value ^= pivot[bit];
  18. }
  19. }
  20. bool varies(int bit) const {
  21. for (ull value : pivot) if ((value >> bit) & 1ULL) return true;
  22. return false;
  23. }
  24. };
  25. long long mod_power(long long base, int exponent) {
  26. long long result = 1;
  27. while (exponent > 0) {
  28. if (exponent & 1) result = result * base % MOD;
  29. base = base * base % MOD;
  30. exponent >>= 1;
  31. }
  32. return result;
  33. }
  34. int main() {
  35. ios::sync_with_stdio(false);
  36. cin.tie(nullptr);
  37. int n, m;
  38. cin >> n >> m;
  39. struct Edge { int to; ull weight; };
  40. vector<vector<Edge>> graph(n);
  41. for (int i = 0; i < m; ++i) {
  42. int u, v;
  43. ull w;
  44. cin >> u >> v >> w;
  45. --u; --v;
  46. graph[u].push_back({v, w});
  47. graph[v].push_back({u, w});
  48. }
  49. vector<char> seen(n, false);
  50. vector<ull> potential(n, 0);
  51. long long answer = 0;
  52. for (int root = 0; root < n; ++root) {
  53. if (seen[root]) continue;
  54. vector<int> component;
  55. vector<int> stack{root};
  56. seen[root] = true;
  57. while (!stack.empty()) {
  58. int v = stack.back();
  59. stack.pop_back();
  60. component.push_back(v);
  61. for (const Edge &edge : graph[v]) {
  62. if (!seen[edge.to]) {
  63. seen[edge.to] = true;
  64. potential[edge.to] = potential[v] ^ edge.weight;
  65. stack.push_back(edge.to);
  66. }
  67. }
  68. }
  69. LinearBasis basis;
  70. for (int v : component) {
  71. for (const Edge &edge : graph[v]) {
  72. basis.insert(potential[v] ^ potential[edge.to] ^ edge.weight);
  73. }
  74. }
  75. long long combinations = mod_power(2, basis.rank);
  76. long long pairs = 1LL * component.size() * (component.size() - 1) / 2 % MOD;
  77. for (int bit = 0; bit < BITS; ++bit) {
  78. long long count;
  79. if (basis.varies(bit)) {
  80. count = pairs * mod_power(2, basis.rank - 1) % MOD;
  81. } else {
  82. long long ones = 0;
  83. for (int v : component) ones += (potential[v] >> bit) & 1ULL;
  84. count = ones % MOD * ((component.size() - ones) % MOD) % MOD;
  85. count = count * combinations % MOD;
  86. }
  87. answer = (answer + count * ((1ULL << bit) % MOD)) % MOD;
  88. }
  89. }
  90. cout << answer << '\n';
  91. return 0;
  92. }