Super Subarray Gym - 101498G(枚举+思维)

题目链接:https://vjudge.net/problem/Gym-101498G

**题目:**In this problem, subarray is defined as non-empty sequence of consecutive elements.

We define a subarray as Super Subarray if the summation of all elements in the subarray is divisible by each element in it.

Given an array a of size n, print the number of Super Subarrays in a.

Input
The first line of the input contains a single integer T (1 ≤ T ≤ 100), the number of test cases.

The first line of each test case contains one integer n (1 ≤ n ≤ 2000), the length of array a.

The second line of each test case contains the sequence of elements of the array a1, a2, …, an (1 ≤ ai ≤ 109), ai is the i-th element of the array a.

Output
For each test case, print a single integer that represents the number of Super Subarrays in a, on a single line.

Example
Input
2
5
1 2 3 4 5
5
2 3 4 3 6
Output
6
6

题意:输入n个数,求有多少个超级子串,当连续子串中所有数的和能 整除子串中的每一个数,那么这个字串为超级字串。

思路:既然求是否能整除每一个数,就可以转化求子串里这些数的最小公倍数,然后看子串中所有数的和是否能整除它们的最小公倍数即可。 可以直接枚举所有的子串,当它们的最小公倍数大于题目中给的最大的所有数之和(2e12)就跳出循环,详情见代码解析。

代码:

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <string>

using namespace std;

const long long inf =2e12;
const int maxn =2000+5;

long long a[maxn],sum[maxn];

long long gcd(long long x,long long y)
{
    if(y==0) return x;
    else return(gcd(y,x%y));

}

int main()
{
    int T,n;
    long long lcm,add_sum,ans,flag;

    scanf("%d",&T);
    while(T--)
    {
        ans=0;
        scanf("%d",&n);
        sum[0]=0;
        lcm=1;

        for(int i=1; i<=n; i++)
        {
            scanf("%lld",&a[i]);
            sum[i]=sum[i-1]+a[i];
        }

        for(int i=1; i<=n; i++)
        {
            add_sum=a[i];
            lcm=a[i];
            for(int j=i; j<=n; j++)
            {
                if(i==j)
                {
                    ans++;
                    continue;
                }
                add_sum+=a[j];
                flag=lcm/gcd(lcm,a[j]);//当前的最小公倍数lcm=flag*a[j],a[j]先不乘,以防爆数据

                if(a[j]>inf/flag)   //最小公倍数lcm=flag*a[j],这样判断就防止了爆数据
                break;//最小公倍数大于inf了
                else
                {
                    lcm=flag*a[j];
                    if(add_sum%lcm==0)
                        ans++;
                }

            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值