标签:
题目链接:赛车
解析:用down[]数组记录每个节点能向下走得最大深度,然后再枚举两个不在同一集合内的两点连接(若在同一集合,则会成环)。
AC代码:
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> using namespace std; int first[100005], nxt[100005], to[100005], e; int d[100005]; int down[100005]; int n; int fa[100005]; bool vis[100005]; int tail, len; void dfs(int u, int dis){ down[u] = 0; d[u] = dis; if(dis > len){ len = dis; tail = u; } for(int i=first[u]; i!=-1; i=nxt[i]){ int v = to[i]; if(d[v] == -1){ fa[v] = u; dfs(v, dis+1); } down[u] = max(down[u], down[v]+1); } } int main(){ // freopen("in.txt", "r", stdin); while(scanf("%d", &n) == 1){ tail = len = 0; memset(first, -1, sizeof(first)); e = 0; for(int i=0; i<n; i++){ int u, v; scanf("%d %d", &u, &v); nxt[e] = first[u]; to[e] = v; first[u] = e++; } memset(d, -1, sizeof(d)); memset(fa, -1, sizeof(fa)); dfs(1, 0); int last = tail; while(last != -1){ vis[last] = true; last = fa[last]; } int ans = len; for(int i=1; i<=n; i++){ if(vis[i]) continue; ans = max(ans, len+down[i]+1); } printf("%d\n", ans); } return 0; }
版权声明:本文为sxk原创文章,转载请附加本文链接^_^
标签:
原文地址:http://blog.csdn.net/u013446688/article/details/48138353