結果

問題 No.1207 グラフX
ユーザー penguinmanpenguinman
提出日時 2020-08-08 15:57:00
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,840 bytes
コンパイル時間 1,763 ms
コンパイル使用メモリ 172,256 KB
実行使用メモリ 41,964 KB
最終ジャッジ日時 2024-04-09 19:37:09
合計ジャッジ時間 10,007 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 TLE -
testcase_01 -- -
testcase_02 -- -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
testcase_30 -- -
testcase_31 -- -
testcase_32 -- -
testcase_33 -- -
testcase_34 -- -
testcase_35 -- -
testcase_36 -- -
testcase_37 -- -
testcase_38 -- -
testcase_39 -- -
testcase_40 -- -
testcase_41 -- -
testcase_42 -- -
testcase_43 -- -
testcase_44 -- -
testcase_45 -- -
testcase_46 -- -
testcase_47 -- -
testcase_48 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
//事前処理とUnion-Find
using std::cin;
using std::cout;
#define endl "\n"
using std::vector;
using ll=long long;
const int MOD=1e9+7;
struct Union_Find{
    int N;
    vector<int> par;
    Union_Find(int n):N(n){
        par.resize(N);
        for(int i=0;i<N;i++) par[i]=i;
    }
    int root(int X){
        if(par[X]==X) return X;
        return par[X]=root(par[X]);
    }
    bool same(int X,int Y){
        return root(X)==root(Y);
    }
    void unite(int X,int Y){
        X=root(X),Y=root(Y);
        if(X!=Y) par[X]=Y;
    }
};
ll modpow(ll X,ll Y){
    ll ret=1;
    Y%=(MOD-1);
    while(Y--) ret=ret*X%MOD;
    return ret;
}
void dfs(int N,int X,int now,vector<bool> &seen,vector<vector<int>> &edge,vector<vector<int>> &weight,vector<int> &subtree,ll &ans){
    seen[now]=1;
    for(int i=0;i<edge[now].size();i++){
        int next=edge[now][i];
        if(!seen[next]){
            dfs(N,X,next,seen,edge,weight,subtree,ans);
            subtree[now]+=subtree[next];
            ans+=modpow(X,weight[now][i])*subtree[next]%MOD*(N-subtree[next])%MOD;
            ans%=MOD;
        }
    }
    subtree[now]++;
}
int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int N,M,X; cin>>N>>M>>X;
    vector<vector<int>> edge(N),weight(N);
    Union_Find UF(N);
    //最小全域木を作る
    for(int i=0;i<M;i++){
        int x,y,z; cin>>x>>y>>z;
        if(!UF.same(x-1,y-1)){
            UF.unite(x-1,y-1);
            edge[x-1].push_back(y-1);
            edge[y-1].push_back(x-1);
            weight[x-1].push_back(z);
            weight[y-1].push_back(z);
        }
    }
    //dfsで各辺が経路になる回数を数えていく
    vector<int> subtree(N);
    vector<bool> seen(N);
    ll ans=0;
    dfs(N,X,0,seen,edge,weight,subtree,ans);
    cout<<ans<<endl;
}
0