• Codeforces 1294F Three Paths on a Tree


    题目链接:

    Codeforces 1294F Three Paths on a Tree

    思路:

    首先三个点中有两个点一定是该树的直径之一的两个端点,我们设为a,b;(不会证明orz)
    还剩一个点c,设len(a,b)len(a,b)是a到b的距离,则答案即为len(a,b)+len(b,c)+len(a,c)2frac{len(a,b)+len(b,c)+len(a,c)}{2}
    因为len(a,b)len(a,b)已经确定是树的直径长度,至于点c,我们遍历所有不是a、b的点,求得最大的len(a,c)+len(b,c)len(a,c)+len(b,c)即可;

    代码:

    #include<bits/stdc++.h>
    
    using namespace std;
    
    inline int read() {
    	int x = 0, f = 1; char c = getchar();
    	while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); }
    	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    	return x * f;
    }
    
    const int maxn = 2e5 + 5;
    vector<int> G[maxn];
    int vst[maxn], sum[maxn];
    int bfs(int u) {
    	memset(vst, 0, sizeof(vst));
    	queue<int> que;
    	que.push(u);
    	int now;
    	while(!que.empty()) {
    		now = que.front();
    		que.pop();
    		for(int & x : G[now]) if(!vst[x] && x != u) {
    			que.push(x);
    			vst[x] = vst[now] + 1;
    		}
    	}
    	return now;
    }
    
    int main() {
    #ifdef MyTest
    	freopen("Sakura.txt", "r", stdin);
    #endif
    	int n = read();
    	for(int i = 1; i < n; i++) {
    		int a = read(), b = read();
    		G[a].push_back(b);
    		G[b].push_back(a);	
    	}
    	int x = bfs(1), y = bfs(x), ans = 0, best;
    	for(int i = 1; i <= n; i++) sum[i] += vst[y] + vst[i];
    	bfs(y);
    	for(int i = 1; i <= n; i++) {
    		sum[i] += vst[i];
    		if(i != x && i != y && sum[i] > ans) ans = sum[i], best = i;
    	}
    	printf("%d
    %d %d %d", ans / 2, x, y, best);
    	return 0;
    }
    
  • 相关阅读:
    EffectComposer + ShaderPass 实现分区特效
    C#树形结构格式化
    vue rules 特殊验证添加
    chrome 下载crx插件 提示 程序包无效 解决方案
    正则表达式 手机、正整数、身份证、Email…
    vue 组件 父组件直接获取$emit 的数据
    响应尺寸
    读取、重写 Web.config文件
    ArcGIS License Manager 服务启动后自动停止
    mianshiti
  • 原文地址:https://www.cnblogs.com/yuhan-blog/p/12308644.html
Copyright © 2020-2023  润新知