Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- const int maxn = 2e5 + 10;
- int n;
- vector<int> graph[maxn];
- int dist_A[maxn], dist_B[maxn];
- pair<int, int> find_diameter() {
- queue<int> q;
- q.push(0);
- q.push(0);
- vector<bool> visited(n, false);
- visited[0] = true;
- int max_dist = 0, max_node1 = -1;
- while(!q.empty()) {
- int node = q.front();
- q.pop();
- int dist = q.front();
- q.pop();
- if(dist > max_dist) {
- max_dist = dist;
- max_node1 = node;
- }
- for(int neighbour : graph[node]) {
- if(!visited[neighbour]) {
- visited[neighbour] = true;
- q.push(neighbour);
- q.push(dist + 1);
- }
- }
- }
- for(int i = 0; i < n; i++) {
- visited[i] = false;
- }
- max_dist = 0;
- int max_node2 = -1;
- q.push(max_node1);
- q.push(0);
- visited[max_node1] = true;
- while(!q.empty()) {
- int node = q.front();
- q.pop();
- int dist = q.front();
- q.pop();
- if(dist > max_dist) {
- max_dist = dist;
- max_node2 = node;
- }
- for(int neighbour : graph[node]) {
- if(!visited[neighbour]) {
- visited[neighbour] = true;
- q.push(neighbour);
- q.push(dist + 1);
- }
- }
- }
- return make_pair(max_node1, max_node2);
- }
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin >> n;
- if(n == 1) {
- cout << 0 << endl;
- return 0;
- }
- for(int i = 0; i < n - 1; i++) {
- int a, b;
- cin >> a >> b;
- a--;
- b--;
- graph[a].push_back(b);
- graph[b].push_back(a);
- }
- pair<int, int> diameter = find_diameter();
- queue<int> q;
- q.push(diameter.first);
- q.push(0);
- vector<bool> visited(n, false);
- visited[diameter.first] = true;
- while(!q.empty()) {
- int node = q.front();
- q.pop();
- int dist = q.front();
- q.pop();
- dist_A[node] = dist;
- for(int neighbour : graph[node]) {
- if(!visited[neighbour]) {
- visited[neighbour] = true;
- q.push(neighbour);
- q.push(dist + 1);
- }
- }
- }
- for(int i = 0; i < n; i++) {
- visited[i] = false;
- }
- q.push(diameter.second);
- q.push(0);
- visited[diameter.second] = true;
- while(!q.empty()) {
- int node = q.front();
- q.pop();
- int dist = q.front();
- q.pop();
- dist_B[node] = dist;
- for(int neighbour : graph[node]) {
- if(!visited[neighbour]) {
- visited[neighbour] = true;
- q.push(neighbour);
- q.push(dist + 1);
- }
- }
- }
- for(int i = 0; i < n; i++) {
- cout << max(dist_A[i], dist_B[i]) << " ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement