# 【CSP-S膜你考】最近公共祖先 （数学）

## Problem A. 最近公共祖先 (commonants.c/cpp/pas)

### 注意

Input file: commonants.in
Output file: commonants.out
Time Limit : 0.5 seconds
Memory Limit: 512 megabytes

### 样例

$\texttt{input\#1}$
2

$\texttt{input\#2}$
19260817

$\texttt{output\#1}$
22

$\texttt{output\#2}$
108973412

### 题解

1.第$i$层的点的个数为$2^i$
2.以第$i$层的点为根节点的子树大小为$2^{n-i+1}-1$
3.以第$i$层的点为$\text{LCA}$的点对个数为$2^{2n-i+1}-2^i$

①它的左子树与右子树上的点的$\text{LCA}$都为根节点。所以点对个数为

$\LARGE\frac{2^{n-i+1}-2}{2} \times \frac{2^{n-i+1}-2}{2}$

$\LARGE= (2^{n-i}-1) \times (2^{n-i}-1)$

$\LARGE= 2^{2n-2i}-2^{n-i+1}+1$

②这棵子树的左子树与根节点的$\text{LCA}$都为根节点。右子树也是。所以有$2^{n-i+1}-2$对点。
③根节点与根节点的$\text{LCA}$也是根节点，点对个数为1。

$\LARGE 2^{2n-2i+1}-1$

$\LARGE 2^{2n-i+1}-2^i$

$\LARGE \sum_{i=0}^{n} (2^{2n-i+1}-2^i) \times i$

$\LARGE =\sum_{i=0}^{n} i \times 2^{2n-i+1}-i \times 2^i$

$\LARGE \sum_{i=0}^{n} i \times 2^{2n-i+1} - \sum_{i=0}^{n} i \times 2^i$

$\LARGE T_n=\sum_{i=0}^{n} i \times 2^{2n-i+1}$

$\LARGE =2^{2n} + 2 \times 2^{2n-1} + 3 \times 2^{2n-2}+...+n \times 2^{n+1}$

$\LARGE 2T_n=2^{2n+1} + 2 \times 2^{2n} + 3 \times 2^{2n-1}+...+n \times 2^{n+2}$

$\Large 2T_n-T_n=2^{2n+1} + 2^{2n} + 2^{2n-1}+...+2^{n+2} - n \times 2^{n+1}$

$\LARGE T_n=2^{2n+1} + 2^{2n} + 2^{2n-1}+...+2^{n+2} - n \times 2^{n+1}$

$\LARGE T_n=\sum_{i=0}^{n} i \times 2^i$

$\LARGE =2 + 2 \times 2^2 + 3 \times 2^3 +...+ n \times 2^n$

$\LARGE 2T_n=2^2 + 2 \times 2^3 + 3 \times 2^4 + ... + n \times 2^{n+1}$

$\LARGE T_n-2T_n=2 + 2^2 + 2^3 +...+2^n- n \times 2^{n+1}$

### $Code$

#include<bits/stdc++.h>
typedef long long ll;
ll n;
const ll mod=1000000007;

ll x=0;bool f=0;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=!f;c=getchar();}
while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
T=f?-x:x;
}

inline ll qpow(ll a,ll b) {
ll ans=1,base=a;
while(b) {
if(b&1) ans=(ans*base)%mod;
base=(base*base)%mod;
b>>=1;
}
return ans%mod;
}

int main() {