結果

問題 No.1207 グラフX
ユーザー 0w1
提出日時 2020-12-19 13:43:06
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 201 ms / 2,000 ms
コード長 1,686 bytes
コンパイル時間 2,445 ms
コンパイル使用メモリ 212,624 KB
最終ジャッジ日時 2025-01-17 03:50:03
ジャッジサーバーID
(参考情報)
judge2 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);

  int N, M, X; { cin >> N >> M >> X; }

  vector<tuple<int, int, int>> edges(M); {
    for (int i = 0; i < M; ++i) {
      int X, Y, Z; { cin >> X >> Y >> Z; --X, --Y; }
      edges[i] = make_tuple(Z, X, Y);
    }
    sort(edges.begin(), edges.end());
  }

  const int D = 1e9 + 7;

  auto ipow = [D](int v, int p) {
    int r = 1;
    for (int i = p; i; i >>= 1) {
      if (i & 1) r = (int64_t) r * v % D;
      v = (int64_t) v * v % D;
    }
    return r;
  };

  int res = 0; {
    vector<vector<pair<int, int>>> g(N); {
      vector<int> fa(N); { iota(fa.begin(), fa.end(), 0); }
      function<int(int)> find = [&](int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); };
      function<bool(int, int)> unite = [&](int x, int y) {
        int fx = find(x);
        int fy = find(y);
        if (fx == fy) return false;
        fa[fx] = fy;
        return true;
      };

      for (auto [w, u, v] : edges) {
        if (unite(u, v)) {
          g[u].emplace_back(w, v);
          g[v].emplace_back(w, u);
        }
      }
    }

    vector<int> sz(N); {
      function<int(int, int)> dfs = [&](int u, int fa) {
        sz[u] = 1;
        for (auto [w, v] : g[u]) if (v != fa) sz[u] += dfs(v, u);
        return sz[u];
      };
      dfs(0, -1);
    }

    function<void(int, int, int)> dfs = [&](int u, int fa, int sup) {
      for (auto [w, v] : g[u]) if (v != fa) {
        int n = (int64_t) (sup + sz[u] - sz[v]) * sz[v] % D;
        (res += (int64_t) n * ipow(X, w) % D) %= D;
        dfs(v, u, sup + sz[u] - sz[v]);
      }
    };

    dfs(0, -1, 0);
  }

  cout << res << endl;
}

0