洛谷P1084疫情控制
考点:树上倍增,贪心,二分答案,链式向前星。
之前见过一个类似的用贪心和枚举答案的题,但没太在意。这道题想到了用贪心想要模拟军队前进,然后删去重复无用的军队,但后来发现是多叉树这样就不能做了
真正的解法:树上倍增预处理,二分枚举答案找到最小的答案(二分枚举需要题目对于但答案有单调性,所有大于或小于的正确答案的值也可以使题目通过,且答案有最小单位,比如这道题一定是整数)然后是用贪心写出检查答案正确的函数。题中的细节很多,需要一步一步的拆解问题。
#include<iostream>
#include<algorithm>
#include<queue>
#include <cstring>
#include<cmath>
using namespace std;
#define ll long long
const int MAX = 6e4;
int n, m, t;//t-log2(n)
int tot = 0, atot = 0, btot = 0, ctot = 0;//计数变量
int to[2 * MAX], edge[2 * MAX], Next[2 * MAX], head[MAX];//链表储存树
bool flag, sta[MAX], need[MAX];//flag-记录有无解,sta-记录结点是否驻扎,need-记录结点是否需要驻扎
int d[MAX], query[MAX], f[MAX][20];//d-结点深度,query-军队起始位置,f-倍增指示终点
ll ans,tim[MAX],ned[MAX],dist[MAX][20];//tim-需要驻扎的结点,ned-处理后仍需要驻扎的结点到根的距离,dist-倍增指示距离
pair<ll, int>h[MAX];
queue<int>q;
void add(int u, int v, int w)//添加链表
{
to[++tot] = v; edge[tot] = w;
Next[tot] = head[u]; head[u] = tot;
}
void bfs()
{
q.push(1);
d[1] = 1;
while (q.size())
{
int x = q.front();
q.pop();
for (int i = head[x]; i; i = Next[i])
{
int y = to[i];
if (d[y])continue;
d[y] = d[x] + 1;
f[y][0] = x;
dist[y][0] = edge[i];
for (int j = 1; j <= t; j++)
{
f[y][j] = f[f[y][j - 1]][j - 1];
dist[y][j] = dist[y][j - 1] + dist[f[y][j - 1]][j - 1];
}
q.push(y);
}
}
}
bool dfs(int x)
{
bool pson = 0;//指示结点是否为叶子节点。
if (sta[x])
return 1;
for (int i = head[x]; i; i = Next[i])
{
int y = to[i];
if (d[y] < d[x])continue;
pson = 1;
if (!dfs(y))return 0;
}
if (!pson)return 0;
return 1;
}
bool check(int lim)
{
memset(sta, 0, sizeof(sta));
memset(tim, 0, sizeof(tim));
memset(ned, 0, sizeof(ned));
memset(h, 0, sizeof(h));
memset(need, 0, sizeof(need));
atot = btot = ctot = 0;
for (int i = 1; i <= m; i++)
{
ll x = query[i], cnt = 0;//统计路程
for (int j = t; j >= 0; j--)
if (f[x][j] > 1 && cnt + dist[x][j] <= lim)
{
cnt += dist[x][j];
x = f[x][j];
}
if (f[x][0] == 1 && cnt + dist[x][0] <= lim)
h[++ctot] = make_pair(lim - cnt - dist[x][0], x);
else sta[x] = 1;
}
for (int i = head[1]; i; i = Next[i])
if (!dfs(to[i]))
need[to[i]] = 1;
sort(h + 1, h + ctot + 1);
for (int i = 1; i <= ctot; i++)
if (need[h[i].second] && h[i].first < dist[h[i].second][0])
need[h[i].second] = 0;
else tim[++atot] = h[i].first;
for (int i = head[1]; i; i = Next[i])
{
if (need[to[i]])
ned[++btot] = dist[to[i]][0];
}
if (atot < btot) return 0;
sort(tim + 1, tim + atot + 1);
sort(ned + 1, ned + btot + 1);
int i = 1, j = 1;
while(i<=btot&&j<=atot)//贪心策略
if (tim[j] >= ned[i])
{
i++, j++;
}
else j++;
if (i > btot)
return 1;
return 0;
}
int main()
{
ll l = 0, r = 0, mid;
cin >> n;
t = log2(n) + 1;
for (int i = 1; i < n; i++)
{
int u, v, w;
cin >> u >> v >> w;
add(u, v, w); add(v, u, w);
r += w;
}
bfs();//树上倍增预处理
cin >> m;
for (int i = 1; i <= m; i++)
cin >> query[i];
while (l <= r)//二分枚举
{
mid = (l + r) >> 1;
if (check(mid))
{
r = mid - 1;
ans = mid;
flag = 1;
}
else l = mid + 1;
}
if (!flag)cout << -1 << endl;
else cout << ans << endl;
return 0;
}