POJ 2631

题意:找一颗树中的最长路。

题解:两边bfs,第一次以任意结点开始,找到一个距离它最远的结点,第二次从该节点开始,找到距离它最远的路,这边是最长路。

View Code
 1 #include<cstdio>

 2 #include<cstring>

 3 #include<algorithm>

 4 using namespace std;

 5 const int N=10005,M=1000000;

 6 int head[N],nc;

 7 struct Edge

 8 {

 9     int to,cost,next;

10 }edge[M];

11 void add(int a,int b,int c)

12 {

13     edge[nc].to=b;edge[nc].cost=c;edge[nc].next=head[a];head[a]=nc++;

14     edge[nc].to=a;edge[nc].cost=c;edge[nc].next=head[b];head[b]=nc++;

15 }

16 int dist[N],stk[N];

17 bool vis[N];

18 int bfs(int k)

19 {

20     memset(dist,0,sizeof(dist));

21     memset(vis,false,sizeof(vis));

22     int f,r;

23     f=r=0;

24     vis[stk[r++]=k]=true;

25     int ans=0,id=k;

26     while(f!=r)

27     {

28         int now=stk[f++];

29         if(dist[now]>ans)

30             ans=dist[id=now];

31         for(int i=head[now];i!=-1;i=edge[i].next)

32         {

33             int to=edge[i].to,cc=edge[i].cost;

34             if(!vis[to])

35             {

36                 vis[to]=true;

37                 dist[to]=dist[now]+cc;

38                 stk[r++]=to;

39             }

40         }

41     }

42     return id;

43 }

44 int main()

45 {

46     int a,b,c;

47     memset(head,-1,sizeof(head));

48     nc=0;

49     while(scanf("%d%d%d",&a,&b,&c)!=EOF)

50         add(a,b,c);

51     printf("%d\n",dist[bfs(bfs(a))]);

52     return 0;

53 }

你可能感兴趣的:(poj)