結果

問題 No.1103 Directed Length Sum
ユーザー kurotemko
提出日時 2020-07-26 21:21:18
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 877 ms / 3,000 ms
コード長 1,146 bytes
コンパイル時間 2,040 ms
コンパイル使用メモリ 200,648 KB
最終ジャッジ日時 2025-01-12 06:21:08
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 22
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:36:14: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   36 |         scanf("%d %d", &a, &b);
      |         ~~~~~^~~~~~~~~~~~~~~~~

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;

vector<vector<long long>> g;
vector<long long> depth;
vector<long long> child;

void dfs(int cur, int pre) {
    child[cur] = 1;
    for(auto next : g[cur]) {
        if(next == pre) continue;
        depth[next] = depth[cur] + 1;
        dfs(next, cur);
        child[cur] += child[next];
    }
    return;
}

int main() {

    int n;
    cin >> n;

    // nの長さを確保
    g.resize(n);
    depth.resize(n);
    child.resize(n);

    // 根を探す用の配列
    vector<bool> s_root(n, true);

    // グラフ作成
    for(int i = 0; i < n-1; ++i) {
        int a, b;
        scanf("%d %d", &a, &b);
        a--; b--;
        g[a].emplace_back(b);
        g[b].emplace_back(a);
        s_root[b] = false;
    }

    // 根を探す
    int root = -1;
    for(int i = 0; i < n; ++i) if(s_root[i] == true) root = i; 

    // 根から探索
    dfs(root, -1);

    // 和の計算
    long long ans = 0;
    for(int i = 0; i < n; ++i) {
        ans += (depth[i]%mod*child[i]%mod) % mod;
        ans %= mod;
    }

    cout << ans << endl;
    return 0;
}
0