问题 J: Master of GCD
时间限制: 1 Sec 内存限制: 128 MB
提交: 603 解决: 86
[提交] [状态] [命题人:admin]
题目描述
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.
【分析】
读这个题其实能感受到出题人的意图,因为题目中满满的提示,首先应该发现这一数组的初始值都为1,这就很特殊,出题人为啥不弄个2呢?而且乘的数比较特数,是两个没有公约数的素数,所以接收到这些信息我们就可以进行下一步的思考了。
因为他们都是从1开始乘的,并且在乘的过程中可能有的数做乘法做了几次,也有可能一次都没有,而最后是要求他们的最大公约数,我们会很自然的想到用线段树进行区间修改,但是对于这个题来说写起来比较困难。
其实我们可以直接想到头,总共就是一堆的1做乘法,再怎么乘最后肯定会 被2或3整除,换句话说是【几个2】和【几个3】累乘出来的。所以可以直接统计对于一个位置来说2出现最少次数和3出现最小次数,最后把它们相乘就是最大公约数了。
而具体实现有一个很巧妙的办法,就是差数组,对于一个区间做相同的操作的时候,我们只需对 l 和 r+1 进行操作就可以了,对于此题就是 N2[ l ]++; N2[ r+1 ]--;
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int maxn=100000+5;
int t;
int n,m;
int l,r,num;
int N2[maxn],N3[maxn];
int a,b,c;
int min2,min3;
long long sum=1;
int main()
{
cin>>t;
while(t--)
{
memset(N2,0,sizeof N2);
memset(N3,0,sizeof N3);
min2=maxn;
min3=maxn;
sum=1;
cin>>n>>m;
while(m--)
{
cin>>a>>b>>c;
if(c==2)
{
N2[a]++;
N2[b+1]--;
}
else
{
N3[a]++;
N3[b+1]--;
}
}
min2=N2[1];
min3=N3[1];
for(int i=2;i<=n;i++)
{
N2[i]+=N2[i-1];
N3[i]+=N3[i-1];
min2=min(min2,N2[i]);
min3=min(min3,N3[i]);
}
for(int i=1;i<=min2;i++)
{
sum=(sum*2)%998244353;
}
for(int i=1;i<=min3;i++)
{
sum=(sum*3)%998244353;
}
cout<<sum<<endl;
}
return 0;
}