C. Friends
C. Friends
题意
对于任一点,求到此点距离不超过6的节点数。
分析
第一次dfs,形成一个以 1 为根的有向树,设 down[i][j] 为以i为根节点,距离 i 点距离不超过 j 的节点数(这些节点都是 i 的子孙节点)
第二次dfs,设 up[i][j] 以 i 为起点,距离 i 点距离不超过 j 的非子孙节点的个数,可根据 down 求得。
code
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
typedef pair<int, int> P;
typedef long long ll;
const int INF = 1e9;
const int MAXN = 1e5 + 10;
int up[MAXN][10], down[MAXN][10];
vector<int> G[MAXN];
void dfs1(int pre, int u)
{
down[u][0] = 1;
for(int i = 0; i < G[u].size(); i++)
{
int v = G[u][i];
if(v == pre) continue;
dfs1(u, v);
for(int j = 1; j <= 6; j++) down[u][j] += down[v][j - 1];
}
}
void dfs2(int pre, int u)
{
up[u][0] = 1;
if(u != pre) for(int i = 1; i <= 6; i++)
up[u][i] += up[pre][i - 1] + down[pre][i - 1] - down[u][i > 2 ? i - 2 : 0];
for(int i = 0; i < G[u].size(); i++)
{
int v = G[u][i];
if(v != pre) dfs2(u, v);
}
}
int main()
{
int T, c = 1;
scanf("%d", &T);
while(T--)
{
int n;
scanf("%d", &n);
for(int i = 0; i <= n; i++) G[i].clear();
memset(up, 0, sizeof up);
memset(down, 0, sizeof down);
for(int i = 0; i < n - 1; i++)
{
int x, y;
scanf("%d%d", &x, &y);
G[x].push_back(y);
G[y].push_back(x);
}
dfs1(1, 1); dfs2(1, 1);
printf("Case #%d:\n", c++);
for(int i = 1; i <= n; i++)
{
int res = 0;
for(int j = 1; j <= 6; j++) res += up[i][j] + down[i][j];
printf("%d\n", res);
}
}
return 0;
}
随机推荐
- 怎么看iOS human interface guidelines中的user control原则
最近离开了老东家,整理整理思路,因为一直做的是微信公众号相关的产品对app的东西有一段时间没有做过了,所以又看了一遍iOS human interface guidelines,看到user cont ...
- 【2017-04-18】Ado.Net C#连接数据库进行增、删、改、查
一.简介 1.ado.net是一门数据库访问技术. 他可以通过程序来操作数据库 2.类库 Connection 类 和数据库交互,必须连接它.连接帮助指明数据库服务器.数据库名字.用户名.密码,和连接 ...
- elasticsearch系列(一) 术语
elasticsearch(以下简称es)是一款开源的搜索引擎,基于apach lucene.最近在做nlp的时候顺便研究一下. 下面是官方列举的术语解释 Near Realtime 接近实时的查询, ...
- 内嵌的Component调用外部的方法
如果一个内嵌的Component控件需要调用外部定义的方法,用outerDocument.方法名来调用,前提是该方法是public的.如:<mx:DataGridColumn headerTex ...
- java获得路径的多种方式
本文讲解java语言中获得运行时路径的多种方式,包括java项目.java web项目.jar.weblogic等多种场景. 一.this.getClass().getClassLoader().ge ...
- 金山助手流氓软件-被进程sjk_daemon.exe坑死
修改完Android工程代码,进入调试阶段时DDMS中报错:The connection to adb is down, and a severe error has occured. 由于之前也碰到 ...
- java集合系列
工作以来,一直对java集合理解的不够全面,不够深入,就是常用的ArrayList/HashMap/Set/List,有时候会用一下LinkedList.一时兴起,可能对TreeSet,HashSet ...
- Ajax与Pjax请求在服务端是如何识别的
我在后台处理ajax和一般的网页请求时,一般是需要额外加个参数进行区分的.比如使用get参数的is_ajax=1,后台判断有is_ajax=1成立时,表明该请求是ajax请求,遂可区分处理.我正在使用 ...
- 在QT中创建文件
最近在做QT东西时遇到在指定路径下创建文件,发现qt中没有直接用的. 主要通过自定义一个createFile()函数来实现,其中需要用到<QFile> <QDir> <Q ...
- dubbo 入门
1 介绍 1.1 背景 随着互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,亟需一个治理系统确保架构有条不紊的演进. 1.2 说明 DUBB ...