Description
YJC最近在學習樹的有關知識。今天,他遇到了這麼一個概念:最近公共祖先。對於有根樹T的兩個結點u、v,最近公共祖先
Input
第一行包含兩個整數n和k,表示T是一棵n層的滿k叉樹。
Output
一行,包含一個整數,表示問題的答案%998244353的值。
Sample Input
3 2
Sample Output
22
Data Constraint
對於30%的數據,滿足2≤n,k≤8;
對於50%的數據,滿足2≤n,k≤1000000;
對於100%的數據,滿足2≤n,k≤998244351。
Hint
LCA深度爲0的點對有31個,深度爲1的點對有14個,深度爲2的點對有4個,所以答案=31*0+14*1+4*2=22。
The Solution
30%的算法 暴力求lca,直接計算。
100%的算法:
手玩出一大波算式,然後整理一下可得出
最後就隨便打了。。
CODE
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#define fo(i,a,b) for (int i=a;i<=b;i++)
#define mo 998244353
#define N 100005
using namespace std;
typedef long long ll;
ll ni,n,k;
ll mi(ll x,int y )
{
ll z = 1;
for (;y;x = x * x % mo,y >>= 1) if (y & 1) z = z * x % mo;
return z;
}
int main()
{
freopen("lca.in","r",stdin);
freopen("lca.out","w",stdout);
scanf("%lld%lld",&n,&k);
ni = mi(mi(k-1,3),mo - 2);
ll ans = (mi(k,2*n) % mo + mo +mo - k - (2*n-1) * mi(k,n) % mo * (k-1) % mo) % mo;
printf("%lld\n",ans * ni % mo);
}