问题 J: Master of GCD

题目描述

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的最小次数即可。

找都能除的

要用快速幂,数太大了

#include<stdio.h>
#include<string.h>
int mod = 998244353;
typedef long long ll;
ll fun(ll a, ll b)//快速幂算法
{
    ll s = 1;
    while (b > 0)
    {
        if (b % 2) s = (s * a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return s;
}
int a[200000], b[200000];
int main()
{
    int n,t,m,i,d;
    scanf("%d", &t);
    while (t--)
    {
        int q, w, e;
        scanf("%d%d", &n, &m);
        memset(a, 0, sizeof(a));
        memset(b, 0, sizeof(b));
        for (i = 0; i < m; i++)
        {
            scanf("%d%d%d", &q, &w, &e);
            if (e == 2)
            {
                a[q]++;
                a[w + 1]--;
            }
            if (e == 3)
            {
                b[q]++;
                b[w + 1]--;
            }
        }
        int min1 = mod, min2 = mod,ans;
        for (i = 1; i <= n; i++)
        {
            a[i]+=a[i - 1];
            b[i]+=b[i - 1];
        }
        for (i = 1; i <=n; i++)
        {
            if (a[i] < min1) min1 = a[i];
            if (b[i] < min2) min2 = b[i];
        }
        ans = fun(2, (ll)min1);
        ans = (ans * fun(3, (ll)min2)) % mod;
        printf("%d\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44017102/article/details/89107292
gcd