题目链接:
BestCoder #83 1003 zxa and leaf
题意:
zxa有一棵含有nn个节点的无根树,包含(n-1)条无向边,点从1到n编号,定义每个点的度数为与这个点相连的边的数量,度数为1的节点被称作这棵树的叶子节点。
zxa想给每个节点设置它的好看度,好看度必须为正整数。他的无根树有m(1≤m≤n)个叶子节点,其中的k(1≤k≤m)个叶子节点的好看度已经确定,zxa只需要设置其他节点的好看度。
zxa很好奇,如果令每条边的难看度是这条边所连接的两个节点的好看度差值的绝对值,整棵树的难看度是所有边的难看度中的最大值,那么这棵树的难看度最小是多少,你能帮助他吗?
分析:
二分查找难看度。然后用bfs从所有已知的叶子结点向上检查。如果是将每个已知叶子结点单独建立一个队列进行检查会TLE,
需要将所有的已知叶子结点都一次性全放进队列中进行bfs。
//数据会爆int!!!
#pragma comment(linker, "/STACK:102400000,102400000")
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#include <queue>
#include <vector>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 50010;int T, n, k, total;
int head[MAX_N], vis[MAX_N];
ll low[MAX_N], high[MAX_N];
pair<int, ll> leaf[MAX_N];struct Edge{int to, next;Edge() {}Edge(int _to, int _next) : to(_to), next(_next) {}
}edge[MAX_N << 1];inline bool bfs(int x)
{queue<int> que;memset(vis, 0, sizeof(vis));memset(high, -1, sizeof(high));memset(low, -1, sizeof(low));//已知叶子结点赋权值,并进队列for(int i = 0; i < k; i++){ int u = leaf[i].first;ll w = leaf[i].second;que.push(u);vis[u] = 1;high[u] = low[u] = w; }while(!que.empty()){int cur = que.front();que.pop();for(int i = head[cur]; i != -1; i = edge[i].next){int to = edge[i].to;ll tmplow = max(low[cur] - x, 1LL); //cur节点对to节点的限制ll tmphigh = high[cur] + x;if(low[to] == -1){ //to节点尚未确定low[to] = tmplow;high[to] = tmphigh;vis[to] = 1;if(low[to] > high[to]) return false;que.push(to);}else {if(tmplow > high[to] || tmphigh < low[to]) return false; //cur节点的限制和to已有限制冲突else if(tmplow <= low[to] && tmphigh >= high[to]) continue; //cur节点的限制太弱了 else{ //通过cur对to加强限制low[to] = max(low[to], low[cur] - x);high[to] = min(high[to], high[cur] + x);if(low[to] > high[to]) return false;que.push(to);} }}}return true;
}inline void AddEdge(int u, int v)
{edge[total] = Edge(v, head[u]);head[u] = total++;edge[total] = Edge(u, head[v]);head[v] = total++;
}int main()
{IOS;cin >> T;while(T--){cin >> n >> k;total = 0;memset(head, -1, sizeof(head));for(int i = 1; i < n; i++){int u, v;cin >> u >> v;AddEdge(u, v);}for(int i = 0; i < k; i++){cin >> leaf[i].first >> leaf[i].second;}//二分查找int HIGH = (int)(1e9), LOW = 0;while(HIGH > LOW){int MID = (HIGH + LOW) >> 1;if(bfs(MID)) HIGH = MID;else LOW = MID + 1;}cout << HIGH << endl;}return 0;
}