C. LR-remainders
题目描述
给你一个长度为
n
n
n 的数组
a
a
a 、一个正整数
m
m
m 和一串长度为
n
n
n 的命令。每条命令要么是字符 “L”,要么是字符 “R”。
按照字符串 s s s 中的顺序处理所有 n n n 命令。处理一条命令的步骤如下:
- 首先,输出数组 a a a 中所有元素除以 m m m 后的乘积余数。
- 然后,如果命令是 “L”,则从数组 a a a 中删除最左边的元素;如果命令是 “R”,则从数组 a a a 中删除最右边的元素。
注意,每次移动后,数组 a a a 的长度都会减少 $$$ ,处理完所有命令后,数组 a a a将为空。
请编写一个程序,按照字符串
s
s
s 中的顺序(从左到右)处理所有命令。
输入
第一行包含一个整数 t t t ( 1 ≤ t ≤ 1 0 4 1 \le t \le 10^4 1≤t≤104 ) - 输入中测试用例的数量。然后是 t t t个测试用例的描述。
输入的每个测试用例由三行组成。
第一行包含两个整数 n n n 和 m m m ( 1 ≤ n ≤ 2 ⋅ 1 0 5 , 1 ≤ m ≤ 1 0 4 1 \le n \le 2\cdot10^5, 1 \le m \le 10^4 1≤n≤2⋅105,1≤m≤104 ) - 数组的初始长度 a a a 和余数取值。
第二行包含 n n n 个整数 a 1 , a 2 , a 3 , … … , a n , ( 1 ≤ a i ≤ 1 0 4 ) a_1,a_2,a_3,……,a_n,(1 \leq a_i \leq10^4) a1,a2,a3,……,an,(1≤ai≤104) - 数组 a a a 的元素。
第三行包含一个字符串 s s s ,由 n n n 字符 "L "和 "R "组成。
保证测试中所有测试用例的
n
n
n 值之和不超过
2
⋅
1
0
5
2\cdot10^5
2⋅105 。
输出
对于每个测试用例,输出
n
n
n 个整数
b
1
,
b
2
,
b
3
,
…
…
,
b
n
,
b_1,b_2,b_3,……,b_n,
b1,b2,b3,……,bn,其中
b
i
b_i
bi 是在开始执行
i
i
i -th 命令时,数组
a
a
a 当前状态的所有元素除以
m
m
m 的乘积的余数。
样例:
输入:
4
4 6
3 1 4 2
LRRL
5 1
1 1 1 1 1
LLLLL
6 8
1 2 3 4 5 6
RLLLRR
1 10000
10000
R
输出:
0 2 4 1
0 0 0 0 0
0 0 0 4 4 4
0
分析:
一开始我想用一个前缀乘积数组,用sum[r] / sum[l-1]表示[l,r]这一段的乘积,通过不断删除边界元素求出乘积取模,但是这会造成爆longlong的问题,既然这样我们是不是可以考虑模逆元,即这个问题的关键在于你想要得到 sum[y] / sum[x] % m,这相当于 (sum[y] * inv(sum[x])) % m,其中 inv(sum[x]) 是 sum[x] 在模 m 意义下的逆元。但是没有说明m是质数,用不了费马小定理,同时sum[l-1]的逆元也不一定存在,所以用逆元的方法似乎也不可行。那么怎么办呢?既然除法不满足模运算的基本运算,那我们能不能转化成乘法呢?我们可以把删去的数放入栈中,最终栈里面第一个元素就是最后进来的也就是最后一个元素,我们可以从后遍历,从最后一个元素开始乘,中间不断取模,因为乘法满足模运算的基本运算,这样就解决了爆longlong的问题,我们只需要记录下来,最后输出即可。
下面是完整代码:
// Problem: C. LR-remainders
// Contest: Codeforces - Codeforces Round 927 (Div. 3)
// URL: https://codeforces.com/contest/1932/problem/C
// Memory Limit: 256 MB
// Time Limit: 2000 ms
//
#include<iostream>
#include<queue>
#include<cstring>
#include<map>
#include<algorithm>
#include<vector>
#include<set>
#include<cmath>
#include<stack>
#include<random>
#include<ctime>
#define ll long long
#define ull unsigned long long
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
#define __int128_t int128
using namespace std;
typedef pair<int, int >PII;
const int INF = 0x3f3f3f3f3f3f3f3f;
const int N = 2e5+10;
void solve(){
int n,m;
cin >> n >> m;
vector<ll> a(n+5);
vector<ll> res(n+5);
for(int i = 1; i<= n;i++){
cin >> a[i];
}
string s;
cin >> s;
int l = 1,r = n;
stack<int> sta;
for(int i = 0; i<n;i++){
if(s[i] == 'L'){
sta.push(l++);
}else {
sta.push(r--);
}
}
ll ans = 1;
for(int i = n;i >= 1;i--){
ll now = a[sta.top()];
sta.pop();
ans = ans * now % m;
res[i] = ans;
}
for(int i = 1; i<= n;i++){
cout << res[i] << " ";
}
cout << endl;
}
int main(){
int t;
ios;
cin >> t;
while(t--){
solve();
}
}