結果

問題 No.277 根掘り葉掘り
ユーザー codershifthcodershifth
提出日時 2016-05-06 20:31:27
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 192 ms / 3,000 ms
コード長 1,549 bytes
コンパイル時間 1,445 ms
コンパイル使用メモリ 166,124 KB
実行使用メモリ 9,744 KB
最終ジャッジ日時 2024-04-15 13:33:11
合計ジャッジ時間 4,586 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,812 KB
testcase_01 AC 2 ms
6,940 KB
testcase_02 AC 1 ms
6,944 KB
testcase_03 AC 2 ms
6,944 KB
testcase_04 AC 2 ms
6,940 KB
testcase_05 AC 2 ms
6,940 KB
testcase_06 AC 2 ms
6,940 KB
testcase_07 AC 2 ms
6,940 KB
testcase_08 AC 2 ms
6,944 KB
testcase_09 AC 183 ms
8,956 KB
testcase_10 AC 173 ms
9,744 KB
testcase_11 AC 184 ms
9,216 KB
testcase_12 AC 189 ms
9,216 KB
testcase_13 AC 192 ms
9,344 KB
testcase_14 AC 175 ms
9,344 KB
testcase_15 AC 178 ms
9,216 KB
testcase_16 AC 178 ms
9,216 KB
testcase_17 AC 178 ms
9,344 KB
testcase_18 AC 176 ms
9,216 KB
testcase_19 AC 175 ms
9,344 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

typedef long long ll;
typedef unsigned long long ull;

#define FOR(i,a,b) for(int (i)=(a);i<(b);i++)
#define REP(i,n) FOR(i,0,n)
#define RANGE(vec) (vec).begin(),(vec).end()

using namespace std;


class Inquisitive
{
public:
    void solve(void)
    {
        int N;
        cin>>N;
        vector<vector<int>> tree(N);
        REP(i,N-1)
        {
            int x, y;
            cin>>x>>y;
            --x, --y;
            tree[x].push_back(y);
            tree[y].push_back(x);
        }
        const int inf = (1<<30);
        vector<int> dist(N,inf);
        queue<int> Q;
        Q.push(0);
        REP(i,N)
        {
            if (tree[i].size() == 1)
            {
                // 葉自身は葉までの距離 0
                dist[i] = 0;
                Q.push(i);
            }
        }
        dist[0] = 0;  // 根自身までは距離 0
        // わかっていないのは幹だけ。よって根と葉から bfs すればよい
        while (!Q.empty())
        {
            int u = Q.front();
            Q.pop();

            for (auto to : tree[u])
            {
                if (dist[to] > dist[u] + 1)
                {
                    dist[to] = dist[u]+1;
                    Q.push(to);
                }
            }

        }
        REP(i,N)
            cout<<dist[i]<<endl;
    }
};

#if 1
int main(int argc, char *argv[])
{
        ios::sync_with_stdio(false);
        auto obj = new Inquisitive();
        obj->solve();
        delete obj;
        return 0;
}
#endif
0