提供一种单位根做法。感谢 @CYFqwq 对我的悉心指导,没有他,我根本就不可能会这个做法。
容易注意到设 C 为 ,Z 为 ,只有和在 意义下不为 才可能是合法的。同时,我们也要求最终序列不能是奇数长度 CZ 交替的。
考虑毫无限制,那么答案为 ,这里 表示 N 的个数。考虑扣去使得答案不合法的 N 的贡献。
这里有一个细节,可以现设所有 N 都是 ,实际上的方案是选择部分数字 。
比如,当前余数就是 ,如果你的 N 做的贡献还是 ,就不合法。这种情况下,相当于求:
也就是,我们要求多项式:
的某部分系数和。
先说结论:以余 为例,答案就是 。其中 为三次单位根。
分析之前,明确一个引理:,这个读者自证不难。
简要分析:
- 时,三项贡献全为 。
- 时,对于同一个组合数,三者贡献分别为 ,由引理,相加为 ,等同于不贡献。
- 时,对于同一个组合数,三者贡献分别为 ,由引理,相加为 ,等同于不贡献。
综上,这就是答案。
具体怎么求,运用二项式定理即可,如 。
对于其他余数情况,我们发现无非就是把多项式 头上的系数多了 或 ,在外面乘上即可。
但是现在产生了极其严峻的问题:我们遍历了 到 ,试图找到 意义下的三次单位根,但是居然没有输出??
于是考虑扩域。将所有数表示为 的形式,就像虚数一样。然后乘法的定义是简单的:,由引理,上式即为 ,剩下的自己化吧。
最终输出的答案 ,考虑其数学意义,其中的 一定为 ,所以不必担惊受怕,输出实数部分即可。
写代码的时候铭记引理内容,遇到 化成 即可。
可以参考代码。
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int mod = 1e9 + 7;
int n , q , cnt[3][2] , m;
const int inv3 = 333333336;
inline int id(char c)
{
if(c == 'C') return 1;
if(c == 'Z') return 2;
if(c == 'N') return 0;
__builtin_unreachable(); assert(false);
}
struct node
{
int a , b;
node() {a = 0 , b = 0;}
node(int x) {a = 0 , b = x;}
node(int x , int y) {a = x , b = y;}
node operator + (const node &qwq) const {return (node){(a + qwq.a) % mod , (b + qwq.b) % mod};}
node operator - (const node &qwq) const {return (node){(a - qwq.a + mod) % mod , (b - qwq.b + mod) % mod};}
node operator * (const node &qwq) const
{
int c = qwq.a , d = qwq.b;
node now;
now.a = (b * c % mod + a * d % mod - a * c % mod + mod) % mod;
now.b = (b * d % mod - a * c % mod + mod) % mod;
return now;
}
};
node fast_mi(node x , int y)
{
node qwq = x , ans = {0 , 1};
while(y)
{
if(y & 1) ans = ans * qwq;
y >>= 1 , qwq = qwq * qwq;
}
return ans;
}
inline node calc(node x , int y)
{
// (x+1)^m * (x^y)
return fast_mi(x + (node){0 , 1} , m) * fast_mi(x , y);
}
int solve()
{
int ans = fast_mi({0 , 2} , m).b;
if(n == 1) return ans;
int sum = (cnt[1][0] + cnt[1][1]) + (cnt[2][0] + cnt[2][1]) * 2 + m;
sum %= 3;
ans -= (calc({mod - 1 , mod - 1} , sum) + calc({1 , 0} , sum) + calc({0 , 1} , sum)).b * inv3 % mod;
if(n & 1) ans -= (cnt[1][0] == 0 && cnt[2][1] == 0) + (cnt[1][1] == 0 && cnt[2][0] == 0);
return (ans + mod) % mod;
}
signed main()
{
scanf("%lld%lld" , &n , &q); string s; cin >> s; s = '_' + s;
for(int i = 1 ; i <= n ; i ++)
{
cnt[id(s[i])][i & 1] ++;
m += (s[i] == 'N');
}
printf("%lld\n" , solve());
while(q --)
{
int pos; char c; scanf("%lld" , &pos); cin >> c;
int old = id(s[pos]);
int nw = id(c);
cnt[old][pos & 1] -- , m -= (old == 0);
s[pos] = c;
cnt[nw][pos & 1] ++ , m += (nw == 0);
printf("%lld\n" , solve());
}
return 0;
}