给出一棵树,找出两条不相交即没有公共点的路径,使得两个路径的长度的乘积最大。
思路:枚举树中的边,将该边去掉,分成两棵树,分别求出这两棵树的直径,乘起来维护一个最大值即可。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 using namespace std; 6 7 const int maxn = 200 + 10; 8 9 int n; 10 11 struct Edge 12 { 13 int u, v, nxt; 14 bool del; 15 }; 16 17 int ecnt; 18 int head[maxn]; 19 Edge edges[maxn * 2]; 20 21 void AddEdge(int u, int v) 22 { 23 edges[ecnt].u = u; 24 edges[ecnt].v = v; 25 edges[ecnt].nxt = head[u]; 26 edges[ecnt].del = false; 27 head[u] = ecnt++; 28 } 29 30 int len, id; 31 32 void dfs(int u, int fa, int dep) 33 { 34 if(dep > len) { len = dep; id = u; } 35 for(int i = head[u]; ~i; i = edges[i].nxt) 36 { 37 if(edges[i].del) continue; 38 int v = edges[i].v; 39 if(v == fa) continue; 40 dfs(v, u, dep + 1); 41 } 42 } 43 44 int main() 45 { 46 memset(head, -1, sizeof(head)); 47 48 scanf("%d", &n); 49 for(int u, v, i = 1; i < n; i++) 50 { 51 scanf("%d%d", &u, &v); 52 AddEdge(u, v); AddEdge(v, u); 53 } 54 55 int ans = 0; 56 57 for(int i = 0; i < ecnt; i += 2) 58 { 59 int u = edges[i].u, v = edges[i].v; 60 edges[i].del = true; 61 edges[i^1].del = true; 62 63 int t1, t2; 64 65 id = u; 66 len = 0; 67 dfs(u, 0, 0); 68 len = 0; 69 dfs(id, 0, 0); 70 t1 = len; 71 72 id = v; 73 len = 0; 74 dfs(v, 0, 0); 75 len = 0; 76 dfs(id, 0, 0); 77 t2 = len; 78 79 ans = max(ans, t1 * t2); 80 edges[i].del = false; 81 edges[i^1].del = false; 82 } 83 84 printf("%d ", ans); 85 86 return 0; 87 }