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 ;
}

最新文章

  1. SQLSERVER单表CRUD通用方法
  2. Linux内核分析学习总结
  3. 移动端click事件延迟300ms的原因以及解决办法
  4. C++头文件,预处理详解
  5. 总结的一些PHP开发中的tips
  6. C++ little errors , Big problem
  7. MySql存储过程—2、第一个MySql存储过程的建立
  8. XAMPP下重置mysql密码
  9. TensorFlow深度学习笔记 Tensorboard入门
  10. C语言使用SQLite3数据库
  11. Castle Windsor 学习-----Installer的几种安装方式
  12. PLT文件 和 DXF文件
  13. 【ShoppingWebCrawler】-基于Webkit内核的爬虫蜘蛛引擎概述
  14. ios手机访问H5页面中$(document).on绑定无效问题
  15. 【转载】C++ vector的用法
  16. 不要再用if(xxx != null)或者try catch NullPointerException了,Optional可以帮你解决
  17. requests库使用:通过cookie跳过验证码登录,并用Session跨请求保持cookie
  18. 一个经典的PHP加密解密算法
  19. web 批量打印
  20. pyhthon 求GPA平均学分绩点

热门文章

  1. python epoll实现异步socket
  2. 关于word文档转成html网页的方法
  3. 【Android】Android软件开发之ListView 详解
  4. eclipse 改变颜色,背景
  5. Python 3 利用 Dlib 实现人脸 68个 特征点的标定
  6. OCR技术浅探:Python示例(5)
  7. 【译】Using Objects to Organize Your Code
  8. mono安装
  9. Java文件IO流的操作总结
  10. VS2010/MFC编程入门之二十四(常用控件:列表框控件ListBox)