问题 B: 会议(树的直径)
题目描述
有一个村庄居住着n个村民,有n-1条路径使得这n个村民的家联通,每条路径的长度都为1。现在村长希望在某个村民家中召开一场会议,村长希望所有村民到会议地点的距离之和最小,那么村长应该要把会议地点设置在哪个村民的家中,并且这个距离总和最小是多少?若有多个节点都满足条件,则选择节点编号最小的那个点。
输入
第一行。一个数n,表示有n个村民。
接下来n-1行,每行两个数字a和b,表示村民a的家和村民b的家之间存在一条路径。
接下来n-1行,每行两个数字a和b,表示村民a的家和村民b的家之间存在一条路径。
输出
一行输出两个数字x和y
x表示村长将会在哪个村民家中举办会议
y表示距离之和的最小值
x表示村长将会在哪个村民家中举办会议
y表示距离之和的最小值
样例输入 Copy
4
1 2
2 3
3 4
样例输出 Copy
2 4
提示
70%数据n<=1000
100%数据n<=50000
100%数据n<=50000
思路:找到树的重心。这是最优的,然后以重心为根,求深度。注意,多个符合条件的点,求最小的。
#pragma comment(linker, "/STACK:1024000000,1024000000")
#pragma GCC optimize(3,"Ofast","inline")
#include <bits/stdc++.h>
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
#define rep(i , a , b) for(register int i=(a);i<=(b);i++)
#define per(i , a , b) for(register int i=(a);i>=(b);i--)
#define ms(s) memset(s, 0, sizeof(s))
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll , ll> pi;
typedef unordered_map<int,int> un_map;
template<class T>
inline void read (T &x) {
x = 0;
int sign = 1;
char c = getchar ();
while (c < '0' || c > '9') {
if ( c == '-' ) sign = - 1;
c = getchar ();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar ();
}
x = x * sign;
}
const int maxn = 1e6 + 10;
const int inf = 0x3f3f3f3f;
const ll INF = ll(1e18);
const int mod = 1e9+7;
const double PI = acos(-1);
#define LOCAL
std::vector<int> e[maxn];
bool v[maxn];
int siz[maxn];
int deep[maxn];
int ans;
int pos;
int n;
void dfs(int x) {
v[x]=1;siz[x]=1;
int ma=0;
int si = e[x].size();
rep(i,0,si-1) {
int y = e[x][i];
if(v[y]) continue;
dfs(y);
siz[x]+=siz[y];
ma=max(ma,siz[y]);
}
ma=max(ma,n-siz[x]);
if(ma<ans) {
ans=ma;
pos=x;
}
if(ma==ans&&pos>x) {
pos=x;
}
}
void dfs2(int x,int fa,int dep) {
deep[x]=dep;
int si = e[x].size();
rep(i,0,si-1) {
int y = e[x][i];
if(y==fa) continue;
dfs2(y,x,dep+1);
}
}
void solve() {
rep(i,1,n-1) {
int u,v;
read(u);read(v);
e[u].push_back(v);
e[v].push_back(u);
}
ans=inf;
dfs(1);
dfs2(pos,pos,0);
ll res = 0;
rep(i,1,n) {
res+=abs(deep[pos]-deep[i]);
}
printf("%d %lld\n",pos,res );
}
int main(int argc, char * argv[])
{
//freopen("/home/yesky/桌面/date.in", "r", stdin);
//freopen("/home/yesky/桌面/date.out", "w", stdout);
while(~scanf("%d",&n)) {
solve();
}
return 0;
}