int d[N]; vector<int>v[N]; int n, m; intBFS(int now){ for (int i = 1; i <= n; i++) d[i] = 1e9; queue<int>q; d[now] = 0; q.push(now); while (!q.empty()) { int top = q.front(); q.pop(); for (int i = 0; i < v[top].size(); i++) { int to = v[top][i]; if (d[to] > d[top] + 1) { d[to] = d[top] + 1; q.push(to); } } } int maxn = 0; int Max = 0; for (int i = 1; i <= n; i++) { if (Max < d[i]) { Max = d[i]; maxn = i; } } return maxn; } intmain(){ scanf("%d",&n) ; for (int i = 1; i < n; i++) { int x, y; scanf("%d%d", &x, &y); v[x].push_back(y); v[y].push_back(x); } printf("%d\n", d[BFS(BFS(1))]); }
int n ,m ,s; voidTopSort(vector<int>&in, vector<int>&dis, vector<bool>&vis){ queue<int>q; for (int i = 1; i <= n; i++) { if (!in[i]) q.push(i); } while (q.size()) { int now = q.front(); q.pop(); for (int i = head[now]; i; i = E[i].next) { in[E[i].to]--; if (vis[now]) { if (dis[E[i].to] > dis[now] + E[i].dis) dis[E[i].to] = dis[now] + E[i].dis; vis[E[i].to] = 1; } if (in[E[i].to] == 0) q.push(E[i].to); } } } intmain(){ scanf("%d%d%d", &n, &m, &s); vector<int>in(n+1, 0); vector<bool>vis(n+1, 0); vector<int>dis(n+1, 2e8); for (int i = 0; i < m; i++) { int x, y, z; scanf("%d%d%d", &x, &y, &z); add(x, y, z); in[y]++; } vis[1] = 1; dis[1] = 0; TopSort(in, dis, vis); for (int i = 1; i <= n; i++) printf("%d ",dis[i]); }
int fa[N][22], dep[N], lg[N]; vector<int>v[N]; voidgetdep(int root, int fath){ dep[root] = dep[fath] + 1; fa[root][0] = fath; for (int i = 1; i <= lg[dep[root]]; i++) { fa[root][i] = fa[fa[root][i-1]][i-1]; } for (int i = 0; i < v[root].size(); i++) { if (v[root][i] != fath) getdep(v[root][i], root); } } intLCA(int x, int y){ if (dep[x] < dep[y]) swap(x, y); while (dep[x] > dep[y]) { int level = lg[dep[x] - dep[y]]; x = fa[x][level - 1]; } if (x == y) return x; for (int k = lg[dep[x]] - 1; k >= 0; k--) { if (fa[x][k] != fa[y][k]) { x = fa[x][k]; y = fa[y][k]; } } return fa[x][0]; } int n, m, s; intmain(){ scanf("%d%d%d",&n,&m, &s); for (int i = 1; i <= n; i++) lg[i] = lg[i-1] + (1<<lg[i-1]==i); for (int i = 1; i < n; i++) { int x, y; scanf("%d%d",&x, &y); v[x].push_back(y); v[y].push_back(x); } getdep(s, 0); for (int i = 1; i <= m; i++) { int x, y; scanf("%d%d",&x, &y); printf("%d\n", LCA(x, y)); } }