题意:
由
n
个点组成的串,要装饰所有点,装饰连续
题解:
容易想到dp,令
dp[i]
表示装饰前i个点的方法,那么转移如下:
dp[i]=∑l=1i−1dp[i−l]∗a[l]
关于卷积和fft网上的资料很多了,比如这篇的第三点,这里说下分治。
也不是第一次遇到了,其实就是cdq分治,但是第一次见cdq分治和fft一起用,询问q巨,具体分治过程:
假设现在要求[l,r]的dp值
先递归求[l,m]的dp值
然后用fft把[l,m]的贡献转移给[m+1,r]
再递归求[m+1,r]的dp值
这里fft用来求a[1..r-l]和dp[l..m]的卷积
还不太懂,但是照着写就ac了。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5+5;
const int mod = 313;
const double PI = acos(-1.0);
const int MX = 524300;
struct Complex{
double real, img;
Complex(){ real = img = 0; }
Complex(double a, double b){ real = a, img = b; }
}A[MX], B[MX], C[MX];
Complex operator + (const Complex& a, const Complex& b){
return Complex(a.real+b.real, a.img+b.img);
}
Complex operator - (const Complex& a, const Complex& b){
return Complex(a.real-b.real, a.img-b.img);
}
Complex operator * (const Complex& a, const Complex& b){
return Complex(a.real*b.real-a.img*b.img, a.real*b.img+b.real*a.img);
}
Complex operator / (const Complex& a, double b){
return Complex(a.real/b, a.img/b);
}
void rev(Complex* a, int n){
for(int i = 1, j = n/2; i < n-1; ++i){
if(i < j) swap(a[i], a[j]);
int k = n/2;
while(j >= k) j -= k, k /= 2;
if(j < k) j += k;
}
}
void fft(Complex *a, int n, int f){
rev(a, n);
for(int s = 1; (1<<s) <= n; ++s){
int m = (1<<s);
Complex wm = Complex(cos(f*2*PI/m), sin(f*2*PI/m));
for(int k = 0; k < n; k += m){
Complex w = Complex(1, 0);
for(int j = 0; j < m/2; ++j){
Complex u = a[k+j];
Complex t = w*a[k+j+m/2];
a[k+j] = u + t;
a[k+j+m/2] = u - t;
w = w*wm;
}
}
}
if(f == -1) for(int i = 0; i < n; ++i) a[i] = a[i] / n;
}
ll a[N];
int dp[N]; // dp[i] = SIGMA(dp[j]*a[i-j]) ( 1<= j <= i-1 )
int n;
void cdq(int l, int r){
if(l == r){
dp[l] += a[l];
dp[l] %= mod;
return;
}
int mid = (l+r) >> 1;
cdq(l, mid);
int len = 1;
while(len <= (r-l+1)) len <<= 1;
for(int i = 0; i < len; ++i) A[i] = B[i] = Complex(0, 0);
for(int i = l; i <= mid; ++i) A[i-l] = Complex(dp[i], 0);
for(int i = 1; i <= r-l; ++i) B[i-1] = Complex(a[i], 0);
fft(A, len, 1);
fft(B, len, 1);
for(int i = 0; i < len; ++i) A[i] = A[i]*B[i];
fft(A, len, -1);
for(int i = mid+1; i <= r; ++i){
dp[i] += int(A[i-l-1].real+0.005);
dp[i] %= mod;
}
cdq(mid+1, r);
}
int main(){
while(scanf("%d", &n), n){
for(int i = 1; i <= n; ++i) scanf("%lld", a+i), dp[i] = 0;
for(int i = 1; i <= n; ++i) a[i] %= mod;
dp[0] = 0;
cdq(1, n);
printf("%d\n", dp[n]);
}
}