ZOJ 3820 Building Fire Stations(二分+BFS)



题意:给定一棵树,希望选取两个结点做消防站,使得其余的节点到达消防站的距离最大值最小。

思路:二分这个距离,以任意一个节点为根dfs,找到距离最远的那个点,然后从这个点往上走len个长度,找到当前的这个点,然后在bfs一次找到最远的那个点然后再bfs一次......不过貌似有更优美的做法没仔细研究,dfs会爆栈所以用bfs。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<ctime>
#define eps 1e-6
#define LL long long
#define pii pair<int, int>
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;

const int maxn = 300000;
//const int INF = 0x3f3f3f3f;
int n;
vector<int> G[maxn];
int dep[maxn], m1[maxn], pos[maxn], pa[maxn], dist[maxn];
void bfs(int cur, int fa, int d) {
	queue<int> q;
	q.push(cur);
	dep[cur] = d;
	m1[cur] = 0;
	pos[cur] = cur;
	pa[cur] = fa;
	while(!q.empty()) {
		int t = q.front(); q.pop();
		for(int i = 0; i < G[t].size(); i++) {
        	int u = G[t][i];
        	if(u == pa[t]) continue;
        	dep[u] = dep[t] + 1;
        	pa[u] = t;
        	if(dep[u] > m1[cur]) m1[cur] = dep[u], pos[cur] = u;
        	q.push(u);
    	}
	}
}
int fuck, gan;
bool check(int len) {
    bfs(1, 0, 0);
	if(m1[1] <= len) {
		fuck = 1;
		gan = 2;
		return 1;
	}
    int tmp = 0;
    int p = pos[1];
	while(tmp<len) {
        p = pa[p]; tmp++;
    }
    fuck = p;
    bfs(p, 0, 0);
    if(m1[p] <= len) {
    	if(fuck==1) gan = fuck+1;
    	else gan = 1;
		return 1;
	}
	for(int i = 1; i <= n; i++) dist[i] = dep[i];
    tmp = 0;
    p = pos[p];
	while(tmp<len) {
        p = pa[p]; tmp++;
    }
    gan = p;
    bfs(p, 0, 0);
    for(int i = 1; i <= n; i++) dist[i] = min(dep[i], dist[i]);
	for(int i = 1; i <= n; i++) if(dist[i]>len) return 0;
	return 1;
}
int main() {
    //freopen("input.txt", "r", stdin);
	int T; cin >> T;
	while(T--) {
        cin >> n;
        for(int i = 1; i <= n; i++) G[i].clear();
        for(int i = 1; i < n; i++) {
            int u, v; scanf("%d%d", &u, &v);
            G[u].push_back(v);
            G[v].push_back(u);
        }
        int l = 0, r = n;
        while(l < r) {
            int mid = (l+r) >> 1;
            if(check(mid)) r = mid;
            else l = mid + 1;
        }
        check(r);
        cout << r << " " << min(fuck, gan) << " " << max(fuck, gan) << endl;
	}
    return 0;
}

















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值