题目描述
Hakase has n numbers in a line. At fi rst, they are all equal to 1. Besides, Hakase is interested in primes. She will choose a continuous subsequence [l, r] and a prime parameter x each time and for every l≤i≤r, she will change ai into ai*x. To simplify the problem, x will be 2 or 3. After m operations, Hakase wants to know what is the greatest common divisor of all the numbers.
输入
The first line contains an integer T (1≤T≤10) representing the number of test cases.
For each test case, the fi rst line contains two integers n (1≤n≤100000) and m (1≤m≤100000),where n refers to the length of the whole sequence and m means there are m operations.
The following m lines, each line contains three integers li (1≤li≤n), ri (1≤ri≤n), xi (xi∈{2,3} ),which are referred above.
输出
For each test case, print an integer in one line, representing the greatest common divisor of the sequence. Due to the answer might be very large, print the answer modulo 998244353.
样例输入
2
5 3
1 3 2
3 5 2
1 5 3
6 3
1 2 2
5 6 2
1 6 2
样例输出
6
2
提示
For the first test case, after all operations, the numbers will be [6,6,12,6,6]. So the greatest common divisor is 6.
思路
找到每位乘2与乘3的最小次数,其的2次幂与3次幂的乘积即为最大公约数
代码实现
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
const int N=100005;
const int mod=998244353;
int T,n,m;
int n1[N],n2[N];
ll quickpow(ll a,ll b)
{
ll ans=1;
while(b)
{
if(b%2!=0) ans=ans*a%mod;
a=a*a%mod;
b/=2;
}
return ans;
}
int main()
{
scanf("%d",&T);
while(T--)
{
memset(n1,0,sizeof(n1));
memset(n2,0,sizeof(n2));
int m1=1e9,m2=1e9;
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
if(c==2)
{
n1[a]++;
n1[b+1]--;
}
else
{
n2[a]++;
n2[b+1]--;
}
}
for(int i=1;i<=n;i++)
{
n1[i]+=n1[i-1];
n2[i]+=n2[i-1];
if(n1[i]<m1) m1=n1[i];
if(n2[i]<m2) m2=n2[i];
}
printf("%lld\n",((quickpow(2,m1)%mod)*(quickpow(3,m2)%mod)%mod));
}
return 0;
}
针对一系列整数,通过记录每项被2或3乘法操作的次数,计算并输出序列的最大公约数模998244353。算法采用前缀和优化多次查询,快速幂计算最终结果。
692

被折叠的 条评论
为什么被折叠?



