結果

問題 No.277 根掘り葉掘り
ユーザー tnoda_tnoda_
提出日時 2015-09-08 17:53:32
言語 C++11
(gcc 11.4.0)
結果
TLE  
実行時間 -
コード長 1,840 bytes
コンパイル時間 756 ms
コンパイル使用メモリ 90,728 KB
実行使用メモリ 42,900 KB
最終ジャッジ日時 2023-09-26 10:08:22
合計ジャッジ時間 6,253 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 11 ms
42,900 KB
testcase_01 AC 9 ms
19,432 KB
testcase_02 AC 10 ms
19,532 KB
testcase_03 AC 9 ms
19,620 KB
testcase_04 AC 71 ms
19,532 KB
testcase_05 AC 41 ms
19,484 KB
testcase_06 AC 40 ms
19,580 KB
testcase_07 AC 39 ms
19,448 KB
testcase_08 AC 9 ms
19,628 KB
testcase_09 AC 74 ms
22,756 KB
testcase_10 TLE -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cstdio>
#include <cstring>
#include <cmath>
#include <climits>
#include <iostream>
#include <iomanip>
#include <list>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <algorithm>
#include <numeric>
#include <functional>

#define FOR(i,a,b) for (int i=(a);i<(b);i++)
#define RFOR(i,a,b) for (int i=(b)-1;i>=(a);i--)
#define REP(i,n) for (int i=0;i<(n);i++)
#define RREP(i,n) for (int i=(n)-1;i>=0;i--)
#define ALL(a) (a).begin(),(a).end()

using namespace std;
typedef long long ll;

int N;
const int MAX_N = 500010;
vector<int> G[MAX_N];
queue<int> q;
int depth_0[MAX_N];
int depth_1[MAX_N];
bool leaves[MAX_N];
bool visited[MAX_N];

void bfs_0() {
  depth_0[1] = 0;
  visited[1] = true;
  q.push(1);
  while (!q.empty()) {
    int v = q.front(); q.pop();
    bool is_leaf = true;
    for (int u : G[v]) {
      if (visited[u]) continue;
      is_leaf = false;
      visited[u] = true;
      depth_0[u] = depth_0[v] + 1;
      q.push(u);
    }
    leaves[v] = is_leaf;
  }
}

void bfs_1(int s) {
  memset(visited, 0, sizeof(visited));
  REP(i,MAX_N) depth_1[i] = MAX_N;
  depth_1[s] = 0;
  visited[s] = true;
  q.push(s);
  while (!q.empty()) {
    int v = q.front(); q.pop();
    for (int u : G[v]) {
      if (visited[u]) continue;
      visited[u] = true;
      if (depth_0[u] <= depth_1[v] + 1) continue;
      depth_1[u] = depth_1[v] + 1;
      q.push(u);
    }
  }
  REP(i,MAX_N) depth_0[i] = min(depth_0[i], depth_1[i]);
}


int main(int argc, char *argv[])
{
  cin.tie(0);
  ios::sync_with_stdio(false);
    
  cin >> N;
  REP(i,N-1) {
    int x, y;
    cin >> x >> y;
    G[x].push_back(y);
    G[y].push_back(x);
  }
  bfs_0();
  REP(i,MAX_N) if (leaves[i]) bfs_1(i);
  REP(i,N) cout << depth_0[i+1] << '\n';
  cout << flush;

  return 0;
}
0