結果

問題 No.277 根掘り葉掘り
ユーザー koprickykopricky
提出日時 2017-08-07 11:48:13
言語 C++11
(gcc 8.5.0)
結果
AC  
実行時間 176 ms / 3,000 ms
コード長 1,578 bytes
コンパイル時間 1,519 ms
使用メモリ 14,424 KB
最終ジャッジ日時 2022-12-04 20:34:42
合計ジャッジ時間 5,321 ms
ジャッジサーバーID
(参考情報)
judge11 / judge16
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
使用メモリ
testcase_00 AC 3 ms
5,848 KB
testcase_01 AC 4 ms
5,748 KB
testcase_02 AC 3 ms
5,852 KB
testcase_03 AC 4 ms
5,752 KB
testcase_04 AC 3 ms
5,760 KB
testcase_05 AC 3 ms
5,844 KB
testcase_06 AC 4 ms
5,944 KB
testcase_07 AC 3 ms
5,756 KB
testcase_08 AC 3 ms
5,888 KB
testcase_09 AC 176 ms
14,424 KB
testcase_10 AC 147 ms
10,636 KB
testcase_11 AC 166 ms
9,872 KB
testcase_12 AC 170 ms
12,252 KB
testcase_13 AC 168 ms
10,048 KB
testcase_14 AC 160 ms
10,336 KB
testcase_15 AC 160 ms
10,460 KB
testcase_16 AC 161 ms
10,176 KB
testcase_17 AC 156 ms
10,348 KB
testcase_18 AC 163 ms
10,056 KB
testcase_19 AC 161 ms
10,144 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define ll long long
#define INF 1000000005
#define MOD 1000000007
#define EPS 1e-10
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define each(a, b) for(auto (a): (b))
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
#define pb push_back
#define show(x) cout <<#x<<" = "<<(x)<<endl
#define spair(p) cout <<#p<<": "<<p.fi<<" "<<p.se<<endl
#define svec(v) cout<<#v<<":";rep(kbrni,v.size())cout<<" "<<v[kbrni];cout<<endl
#define sset(s) cout<<#s<<":";each(kbrni,s)cout <<" "<<kbrni;cout<<endl

using namespace std;

typedef pair<int,int>P;

const int MAX_N = 100005;

vector<int> G[MAX_N];
int d[MAX_N];
vector<int> ha;
int memo[MAX_N];

void dfs(int u,int p,int k)
{
    d[u] = k;
    if(G[u].size() == 1 && G[u][0] == p){
        ha.pb(u);
    }
    rep(i,G[u].size()){
        if(G[u][i] != p){
            dfs(G[u][i],u,k+1);
        }
    }
}

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    rep(i,n-1){
        int a,b;
        cin >> a >> b;
        G[a-1].pb(b-1);
        G[b-1].pb(a-1);
    }
    dfs(0,-1,0);
    rep(i,n){
        memo[i] = INF;
    }
    queue<int> que;
    rep(i,ha.size()){
        memo[ha[i]] = 0;
        que.push(ha[i]);
    }
    while(!que.empty()){
        int p = que.front();
        que.pop();
        rep(i,G[p].size()){
            if(memo[G[p][i]] > memo[p]+1){
                memo[G[p][i]] = memo[p]+1;
                que.push(G[p][i]);
            }
        }
    }
    rep(i,n){
        cout << min(d[i],memo[i]) << endl;
    }
    return 0;
}
0