The diameter of the codeforces 14d two paths tree

Source: Internet
Author: User

Question link: Click the open link

Give a tree

Find two paths with no duplicates to maximize the length product of the two paths.

Ideas:

1. To ensure that vertices are not repeated, delete an edge in the graph and enumerate the deleted edge.

2. In this way, we get two trees, and find the longest chain in their respective trees, that is, the diameter of the tree, and then multiply them.

#include<stdio.h>#include<iostream>#include<string.h>#include<set>#include<vector>#include<map>#include<math.h>#include<queue>#include<string>#include<stdlib.h>#include<algorithm>using namespace std;#define N 220struct Edge {int from, to, nex;bool hehe;}edge[N<<1];int head[N], edgenum;void add(int u, int v){Edge E={u,v,head[u],true};edge[edgenum] = E;head[u] = edgenum ++;}int n;int dis[N];void init(){ memset(head, -1, sizeof head);edgenum = 0; }int bfs(int x){memset(dis, 0, sizeof dis);dis[x] = 1;queue<int>q; q.push(x);int hehe = x;while(!q.empty()) {int u = q.front(); q.pop();for(int i = head[u]; ~i; i = edge[i].nex) {if(!edge[i].hehe)continue;int v = edge[i].to;if(dis[v])continue;dis[v] = dis[u]+1, q.push(v);if(dis[hehe]<dis[v])hehe = v;}}return hehe;}int main(){int i, u, v;while(~scanf("%d",&n)){init();for(i=1;i<n;i++){scanf("%d %d",&u,&v);add(u,v); add(v,u);}int ans = 0;for(i = 0; i < edgenum; i+=2){edge[i].hehe = edge[i^1].hehe = false;u = edge[i].from; v = edge[i].to;int L1 = bfs(u); int R1 = bfs(L1);int mul1 = dis[R1] -1;int L2 = bfs(v); int R2 = bfs(L2);int mul2 = dis[R2] -1;ans = max(ans, mul1 * mul2);edge[i].hehe = edge[i^1].hehe = true;}printf("%d\n",ans);}return 0;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.