Archives
Trending
Support
Login
clear text
XML
Django
JavaScript
MATLAB
C
C++
C#
Python
SQL
Shell
Bash
Markdown
YAML
JSON
HTML
CSS
PHP
Java
Ruby
Go
Rust
Swift
Kotlin
Arduino
TypeScript
Perl
Autohotkey
Lua
SQF
R
Scala
Haskell
Groovy
Dart
Clojure
VB.NET
Objective-C
PowerShell
Bash
CoffeeScript
Verilog
#include
#include
#include
using namespace std; const int maxn = 2e5 + 10; int n; vector
graph[maxn]; int dist_A[maxn], dist_B[maxn]; pair
find_diameter() { queue
q; q.push(0); q.push(0); vector
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
diameter = find_diameter(); queue
q; q.push(diameter.first); q.push(0); vector
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; }
Mark as private (unlisted)
for 30 minutes
for 6 hours
for 1 day
for 1 week
for 1 month
for 1 year
everlasting (like CCCP)