【题目链接】

点击打开链接

【算法】

预处理i^k的前缀和,对于每次询问,树上倍增即可

时间复杂度 : O(nk + mlog(n))

【代码】

#include<bits/stdc++.h>
using namespace std;
#define MAXK 55
#define MAXN 300010
#define MAXLOG 20
const long long P = ; struct Edge
{
int to,nxt;
} e[MAXN<<];
int n,x,i,j,y,q,k,Lca,tot;
int anc[MAXN][MAXLOG],dep[MAXN],head[MAXN],fa[MAXN];
long long p[MAXN][MAXK],s[MAXN][MAXK];
long long ans; template <typename T> inline void read(T &x)
{
int f = ; x = ;
char c = getchar();
for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
for (; isdigit(c); c = getchar()) x = (x << ) + (x << ) + c - '';
x *= f;
}
template <typename T> inline void write(T x)
{
if (x < )
{
putchar('-');
x = -x;
}
if (x > ) write(x/);
putchar(x%+'');
}
template <typename T> inline void writeln(T x)
{
write(x);
puts("");
}
inline void add(int x,int y)
{
tot++;
e[tot] = (Edge){y,head[x]};
head[x] = tot;
}
inline void dfs(int u)
{
int i,v;
anc[u][] = fa[u];
for (i = ; i < MAXLOG; i++)
{
if (dep[u] < ( << i)) break;
anc[u][i] = anc[anc[u][i-]][i-];
}
for (i = head[u]; i; i = e[i].nxt)
{
v = e[i].to;
if (fa[u] != v)
{
fa[v] = u;
dep[v] = dep[u] + ;
dfs(v);
}
}
}
inline int lca(int x,int y)
{
int i,t;
if (dep[x] > dep[y]) swap(x,y);
t = dep[y] - dep[x];
for (i = ; i < MAXLOG; i++)
{
if (t & ( << i))
y = anc[y][i];
}
if (x == y) return x;
for (i = MAXLOG - ; i >= ; i--)
{
if (anc[x][i] != anc[y][i])
{
x = anc[x][i];
y = anc[y][i];
}
}
return fa[x];
} int main()
{ read(n);
for (i = ; i < n; i++)
{
read(x); read(y);
add(x,y);
add(y,x);
}
for (i = ; i < n; i++)
{
p[i][] = ;
for (j = ; j < MAXK; j++) p[i][j] = p[i][j-] * i % P;
}
for (i = ; i < n; i++)
{
for (j = ; j < MAXK; j++)
{
s[i][j] = (s[i-][j] + p[i][j]) % P;
}
}
dfs();
read(q);
while (q--)
{
read(x); read(y); read(k);
Lca = lca(x,y);
ans = (s[dep[x]][k] + s[dep[y]][k]) % P;
ans = ((ans - ( * s[dep[Lca]][k]) % P) + P) % P;
ans = (ans + p[dep[Lca]][k] + P) % P;
writeln(ans);
} return ; }

最新文章

  1. 【原】关于使用sklearn进行数据预处理 —— 归一化/标准化/正则化
  2. Delphi编程获取系统当前进程、窗口句柄、文件属性以(转)
  3. 【PHP用户的错误日志】
  4. Linux Kernel 3.11 正式版发布
  5. 北京地铁月度消费总金额计算(Python版)
  6. Sonar+Hudson+Maven构建系列之三:安装Hudson
  7. scjp考试准备 - 5 - 重载和重写
  8. java中print\println\printf的区别
  9. 提高iOS开发效率的方法和工具
  10. css3学习笔记之背景
  11. Linux ---&gt; 简单socket
  12. Jquery 实现瀑布流布局
  13. Red Hat linux 如何增加swap空间
  14. PL/SQL Developer 远程连接Oracle数据库
  15. char类型关联
  16. twitter接口开发
  17. &lt;?php function say() { echo &#39;hello world&#39;; } //在这里调用函数 say(); php 调用方法say()
  18. Git学习 -- 新建版本库
  19. OSGI框架中通过BundleContext对象对服务的注册与引用
  20. HTML标签类型及特点

热门文章

  1. squid正向代理使用
  2. db2,差集
  3. [bzoj2822][AHOI2012]树屋阶梯 (卡特兰数+分解质因数+高精度)
  4. LIBSVM使用方法及参数设置
  5. Spring Boot Jpa 表名小写转大写
  6. Word Search(深度搜索DFS,参考)
  7. Servlet实现页面重定向
  8. 使用Post方法模拟登陆爬取网页(转)
  9. linux网络编程中的shutdown()与close()函数
  10. Vue中-下拉框可以选择可以填写