题解:P7489 「Stoi2031」手写的从前

· · 题解

一道思维流畅的数学推导题目~ 本题解大量使用归纳,帮助大家理解过程~

题目描述

令 f_0(S)=\dfrac{\sigma(S)}{\pi(S)},f_k(S)=\sum\limits_{T \subseteq S}f_{k-1}(T)。其中 \sigma(S)=\sum\limits_{x \in S}x 为 S 中所有元素之和, \pi(S)=\prod\limits_{x \in S}x 为 S 中所有元素之积。给定 n,k,p 和集合 S,求 f_k(S) \bmod{p} 的值。

推导过程

不难举出两个特例:

f_1(S) =\sum\limits_{T \subseteq S}f_{0}(T)=\sum\limits_{T \subseteq S}1^{|S|-|T|}f_0(T)\\ f_2(S) =\sum\limits_{T_1 \subseteq S}\sum\limits_{T \subseteq T_1}f_{0}(T)=\sum\limits_{T \subseteq S}2^{|S|-|T|}f_0(T)$\ 综上:注意到 $f_m(S) =\sum\limits_{T \subseteq S}m^{|S|-|T|}f_0(T)$ \ 于是存在 $f_m(S)=\sum\limits_{T \subseteq S}m^{|S|-|T|}\dfrac{\sigma(T)}{\pi(T)}=\frac{\sum\limits_{T \subseteq S}m^{|S|-|T|}\sigma(T)\pi(S-T)}{\pi(S)}\\

不妨定义: g(i) 表示 S 取前 i 个元素时的 \sum\limits_{T \subseteq S}m^{|S|-|T|}\sigma(T)\pi(S-T) ,定义 h(i)=\sum\limits_{T \subseteq S}m^{|T|}\pi(T)\\ 举例展开 g 不难注意到:\

$h(i)=ma_ih(i-1)+h(i-1)$\ 综上 $f_k(S)\equiv g(|S|)\pi(S)^{-1} \pmod p

注意!h函数的递推初值为1(因为定义为乘法),而g为0。

代码实现

最后的坑点就是变量类型, long long 太小, int128 取模太慢,所以用 int128 作为临时变量,用快读快写优化一下,其它就没有什么问题了
最后的结果用一下逆元,其他就是套公式啦~
上代码~

#include <bits/stdc++.h>
using namespace std;

#define int long long

int a[7000005];

int exgcd(int a, int b, int &x, int &y)
{
    if (!b)
    {
        x = 1;
        y = 0;
        return a;
    }
    int ans = exgcd(b, a % b, y, x);
    y -= a / b * x;
    return ans;
}

char *p1, *p2, buf[7000000];
#define nc() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1,100000, stdin), p1 == p2) ? EOF : *p1++)
int read()
{
    int x = 0,f = 1;
    char ch = nc();
    while(ch < 48 || ch > 57)
    {
        if(ch == '-')
            f = -1;
        ch = nc();
    }
    while (ch >= 48 && ch <= 57)
        x = x * 10 + ch - 48, ch = nc();
    return x * f;
}

void write(int x)
{
    if(x < 0)
        putchar('-'), x=-x;
    if(x > 9)
        write(x / 10);
    putchar(x % 10 + '0');
    return;
}

signed main()
{
    int n, k, p;
    n = read();
    k = read();
    p = read();
    int pi = 1;
    for (register int i = 1; i <= n; i++)
    {
        a[i] = read();
        pi = pi * a[i] % p;
    }
    int t;
    int h = 1, g = 0;
    for (register int i = 1; i <= n; i++)
    {
        g = (((g + (__int128)k * a[i] % p * g % p) % p + p) % p + ((__int128)a[i] * h % p + p) % p) % p;
        h = ((((__int128)k * a[i] % p * h % p + p) % p + h) % p+ p) % p;
    }
    int tmp = 0, inv = 0;
    exgcd(pi, p, inv, tmp);
    inv = (inv % p + p) % p;
    write((__int128)g * inv % p);
    return 0;
}