A - 口算训练

点击打开链接

小Q非常喜欢数学,但是他的口算能力非常弱。因此他找到了小T,给了小T一个长度为 n的正整数序列 a1,a2,...,an,要求小T抛出 m个问题以训练他的口算能力。

每个问题给出三个正整数 l,r,d,小Q需要通过口算快速判断 al×al+1×...×ar1×ar是不是 d
的倍数。

小Q迅速地回答了出来,但是小T并不知道正确答案是什么,请写一个程序帮助小T计算这些问题的正确答案。
Input 第一行包含一个正整数 T(1T10),表示测试数据的组数。

每组数据第一行包含两个正整数 n,m(1n,m100000),分别表示序列长度以及问题个数。

第二行包含 n个正整数 a1,a2,...,an(1ai100000),表示序列中的每个数。

接下来 m行,每行三个正整数 l,r,d(1lrn,1d100000),表示每个问题。 Output 对于每个问题输出一行,若是倍数,输出Yes,否则输出No。 Sample Input
1
5 4
6 4 7 2 5
1 2 24
1 3 18
2 5 17
3 5 35
Sample Output
Yes
No
No
Yes
思路: 我们对输入的每一个数字分解质因数,分解过程中把下标存入对应的质因子中数组中。然后对于每次查询l,r,d,我们只需要对d分解质因数,然后统计当前这个质因数(假设为i)的个数cnt,如果cnt大于在L~R区间中 i 的个数那么就不行。那么怎么寻找在L~R区间中的 i 的个数呢。

开一个vector<int> ve[100005]。G[i]存的是含有i这个因子的下标。

二分找到 R 的上界 和 L 的下界,相减即可。

lower_bound(first,end,x):

first:要查找区间的起始位置(地址)

end:要查找区间的结束位置(地址)

在first和end区间中返回第一个大于等于x的值的地址


upper_bound(first,end,x):

在first和end区间中返回第一个大于x的值的地址

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
vector <int>ve[100005];
int so(int l,int r,int d)
{
   int i,j;
   for(i=2;i*i<=d;i++)
   {
      int sum=0;
   //将d质因数分解,sum统计d中i因子的个数
    while(d%i==0)
      {
         sum++;
         d/=i;
      }
   if(sum)
   {
       //在区间[l,r]中i的个数
        int t=upper_bound(ve[i].begin(),ve[i].end(),r)-lower_bound(ve[i].begin(),ve[i].end(),l);
        if(t<sum)
         return 0;
   }
  }
  若d为质数,特别判断
  if(d>1)
  {
     int t=upper_bound(ve[d].begin(),ve[d].end(),r)-lower_bound(ve[d].begin(),ve[d].end(),l);
     if(t<1)
       return 0;
  }
  return 1;
}
int main()
{
   int i,j,t,n,m,l,r,d;
   scanf("%d",&t);
   while(t--)
   {
      scanf("%d%d",&n,&m);
      //清空ve[]
      for(i=0;i<100005;i++)
        ve[i].clear();
      int x;
      for(i=1;i<=n;i++)
      {
         scanf("%d",&x);
        //将x质因数分解
         for(j=2;j*j<=x;j++)
         {
            while(x%j==0)
            {
               ve[j].push_back(i);
               x/=j;
            }
         }
         //x是质数
         if(x>1)
           ve[x].push_back(i);
      }
      for(i=0;i<m;i++)
      {
         scanf("%d%d%d",&l,&r,&d);
         if(so(l,r,d))
           printf("Yes\n");
         else
           printf("No\n");
      }
   }
   return 0;
}


猜你喜欢

转载自blog.csdn.net/ac_ac_/article/details/80577295