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