1. 程式人生 > 實用技巧 >HDU6822 Paperfolding(思維/排列組合/逆元)

HDU6822 Paperfolding(思維/排列組合/逆元)

There is a piece of paper in rectangular shape with sufficient length and width (lay flat on the table). Execute an operation instruction according to a string of length n from left to right that only contains 4 different characters of L,R,U,D.

  1. L instruction means to fold it from left to right,

  2. R

    instruction means to fold from right to left,

  3. U instruction means to fold from top to bottom,

  4. D instruction means to fold in half from bottom to top.

Note that the operation is limited due to the limitation of the desktop. Namely, the fold operation is restricted. For example, if you fold the paper from left to right, you should let the left side overlap on the right side with no rotation.

Now, cut a knife horizontally (completely cut) at the center of the visible part of the paper, and then cut vertically (completely cut).

The number of pieces of the whole paper split is num(S).

See the example and the picture for better understanding.

Now given a nonnegative integer n, the string S

S is generated from 4n different possible outcomes in equal probability. Find the expected value of the number of pieces of the paper which is split, that is E(num(S)) mod 998244353.

It can be shown that the answers can be represented by \(\frac{P}{Q}\), where P and Q are coprime integers, and print the value of P×Q−1 mod 998244353.

Input

The first line contains a single integer TT

(1≤T\(10^5\)), the number of testcases.

Each of the next T lines contains a number n ( 0≤n\(10^8\)).

Output

For each testcase, print the answer in one line.

Sample Input

2
0
1

Sample Output

4
6

首先我們注意到,左右折其實是等價的,上下折也是等價的。不妨設左右折了a次,上下折了b次,展開以後這些摺痕總共把紙分成了\(2^a\times2^b\)個區域,每個區域如果橫豎剪開,最終會得到\((2^a+1)\times (2^b+1)\)塊紙(形狀不一定一樣),同時滿足\(a+b=n\)。那麼期望就是\(E=\Sigma^n_{a=1}\frac{C^{a}_{n}}{2^n}\times (2^a+1)\times (2^{n-a}+1)\),展開後可得\(E=2^n+1+\Sigma^n_{a=0}\frac{C^a_{n}}{2^a} +\frac{1}{2^n}\Sigma^{n}_{a=0}2^a\times C^a_n\),後面這兩項可以用二項式定理化簡,得到最終的式子為\(E=2^n+1+\frac{3^n}{2^{n-1}}\)。同樣是分數取模,用到了快速冪和費馬小定理。

#include <bits/stdc++.h>
#define mod 998244353
using namespace std;
long long ksm(long long x,long long y){
    long long a=1;
    while(y){
        if(y&1) a=a*x%mod;
        y>>=1;
        x=x*x%mod;
    }
    return a;
}
int main()
{
	int t;
	cin >> t;
	while(t--)
	{
		long long n;
		scanf("%lld", &n);
		if(!n) cout << 4 << endl;
		else printf("%lld\n", (ksm(2, n) + 1 + ksm(3, n) * ksm(ksm(2, n - 1), mod - 2) % mod) % mod);
	}
	return 0;
}