Gym 101147J Whistle's New Car(dfs)
2024-09-02 13:53:41
https://vjudge.net/problem/Gym-101147J
题意:
有n个城市,每个城市有一个权值,表示在这个城市的加油站可以加多少油。
现在要计算每个城市i,有多少个城市j可以到达它:
① j 是 i 的子树。
② 在城市 j 加满Xj的油后不再加油能到达 i 城市。
思路:
我们从根结点出发,dfs整棵树,在dfs的过程中,我们维护一个道路长度的和sum[],sum[j]就是1到第j个城市的路径之和。
假如我们现在dfs到了第j个城市v,此时1~j的路径之和就是sum[j],然后sum[j]-x[v]就是从v城市出发所能到达的最远距离。
int pos=lower_bound(sum,sum+ret+,sum[ret]-x[v])-sum;
接下来二分查找计算出从v出发在这条路径上所能到达的最远的城市。它所能到达的城市都需要+1。
最后把子节点的个数加到父节点上即可。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
using namespace std;
typedef long long LL;
typedef pair<int,LL> pll;
const int maxn=+; int n;
LL x[maxn];
int vis[maxn];
LL sum[maxn];
int num[maxn];
int cnt[maxn];
int ret;
vector<pll> G[maxn]; void dfs(int u)
{
vis[u]=;
for(int i=;i<G[u].size();i++)
{
int v=G[u][i].first;
int w=G[u][i].second;
if(vis[v]) continue;
sum[ret]=sum[ret-]+w;
num[ret]=v; //路径上第ret城市为v
int pos=lower_bound(sum,sum+ret+,sum[ret]-x[v])-sum;//v出发能到达的最远的城市
if(pos<ret)//如果能到达父结点城市
{
cnt[u]++; //父节点城市数量+1
cnt[num[pos-]]--; //这个一定要减,不然后面子节点的数加到父节点的时候,父节点就多加了
}
ret++;
dfs(v);
ret--;
cnt[u]+=cnt[v];
}
} int main()
{
// freopen("car.in","r",stdin);
//freopen("D:\\input.txt","r",stdin);
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=;i<=n;i++) G[i].clear();
for(int i=;i<=n;i++) scanf("%lld",&x[i]);
for(int i=;i<n;i++)
{
int u,v;
LL d;
scanf("%d%d%lld",&u,&v,&d);
G[u].push_back(make_pair(v,d));
G[v].push_back(make_pair(u,d));
}
memset(vis,,sizeof(vis));
memset(cnt,,sizeof(cnt));
ret=;
sum[]=; //1~路径上第j个城市的距离和
num[]=;
dfs(); //从根结点出发遍历
for(int i=;i<=n;i++)
printf("%d%c",cnt[i],i!=n?' ':'\n');
}
return ;
}
最新文章
- SQLSERVER单表CRUD通用方法
- Linux内核分析学习总结
- 移动端click事件延迟300ms的原因以及解决办法
- C++头文件,预处理详解
- 总结的一些PHP开发中的tips
- C++ little errors , Big problem
- MySql存储过程—2、第一个MySql存储过程的建立
- XAMPP下重置mysql密码
- TensorFlow深度学习笔记 Tensorboard入门
- C语言使用SQLite3数据库
- Castle Windsor 学习-----Installer的几种安装方式
- PLT文件 和 DXF文件
- 【ShoppingWebCrawler】-基于Webkit内核的爬虫蜘蛛引擎概述
- ios手机访问H5页面中$(document).on绑定无效问题
- 【转载】C++ vector的用法
- 不要再用if(xxx != null)或者try catch NullPointerException了,Optional可以帮你解决
- requests库使用:通过cookie跳过验证码登录,并用Session跨请求保持cookie
- 一个经典的PHP加密解密算法
- web 批量打印
- pyhthon 求GPA平均学分绩点