【BJOI 2018】 求和

【题目链接】

           点击打开链接

【算法】

           预处理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 = 998244353;

struct Edge
{
		int to,nxt;
} e[MAXN<<1];
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 = 1; x = 0;
    char c = getchar();
    for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
    for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
    x *= f;
}
template <typename T> inline void write(T x)
{
    if (x < 0)
    {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x/10);
    putchar(x%10+'0');
}
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][0] = fa[u];
		for (i = 1; i < MAXLOG; i++)
		{
				if (dep[u] < (1 << i)) break;
				anc[u][i] = anc[anc[u][i-1]][i-1];
		}
		for (i = head[u]; i; i = e[i].nxt)
		{
				v = e[i].to;
				if (fa[u] != v)
				{
						fa[v] = u;
						dep[v] = dep[u] + 1;
						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 = 0; i < MAXLOG; i++)
		{
				if (t & (1 << i))
						y = anc[y][i];	
		}		
		if (x == y) return x;
		for (i = MAXLOG - 1; i >= 0; 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 = 1; i < n; i++)
		{
				read(x); read(y);
				add(x,y);
				add(y,x);		
		} 
		for (i = 1; i < n; i++)
		{
				p[i][0] = 1;
				for (j = 1; j < MAXK; j++) p[i][j] = p[i][j-1] * i % P;
		}
		for (i = 1; i < n; i++)
		{
				for (j = 1; j < MAXK; j++) 
				{
						s[i][j] = (s[i-1][j] + p[i][j]) % P;
				}
		}
		dfs(1);
		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 - (2 * s[dep[Lca]][k]) % P) + P) % P;
				ans = (ans + p[dep[Lca]][k] + P) % P;
				writeln(ans);
		}
		
		return 0;
	
}

          

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值