【算法】Partitioning the Array(数论)

题目

Allen has an array a1,a2,…,an. For every positive integer k that is a divisor of n, Allen does the following:

  • He partitions the array into n/k disjoint subarrays of length k. In other words, he partitions the array into the following subarrays:

    [a1,a2,…,ak],[ak+1,ak+2,…,a2k],…,[an−k+1,an−k+2,…,an]

  • Allen earns one point if there exists some positive integer m (m≥2) such that if he replaces every element in the array with its remainder when divided by m, then all subarrays will be identical.

Help Allen find the number of points he will earn.

================================================================

Allen 有一个数组 a1,a2,…,an。对于每一个能被 n 整除的正整数 k,艾伦都会做如下运算:

  • 他将数组划分为长度为 k 的 n/k 个互不相交的子数组:

    [a1,a2,…,ak],[ak+1,ak+2,…,a2k],…,[an−k+1,an−k+2,…,an]

  • 如果存在某个正整数 m (m≥2),使得如果他把数组中的每个元素都替换成除以 m 后的余数,那么所有的子数组都是相同的,Allen 就可以得到一分。

帮助艾伦找出他将获得的分数。

Input

Each test consists of multiple test cases. The first line contains a single integer t (1≤t≤104) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer n (1≤n≤2⋅10^5) — the length of the array a.

The second line of each test case contains n integers a1,a2,…,an (1≤ai≤n) — the elements of the array a.

It is guaranteed that the sum of n over all test cases does not exceed 2⋅105.

输入

每个测试由多个测试用例组成。第一行包含一个整数 t(1≤t≤104)–测试用例数。测试用例说明如下。

每个测试用例的第一行包含一个整数 n(1≤n≤2⋅105)–数组 a 的长度。

每个测试用例的第二行包含 n 个整数 a1,a2,…,an(1≤ai≤n)–数组 a 的元素。

保证所有测试用例中 n 的总和不超过 2⋅10^5。

Output

For each test case, output a single integer — the number of points Allen will earn.

输出

对于每个测试用例,输出一个整数 - 艾伦将获得的分数。

思路

本题用到一个概念:如果m为|x-y|的因数,则x % m == y % m.
将数组划分为长度相等的 i 段,将所有的数全部模m之后,所有数组相同。例如当m = 1的时候每个数组中的数均为0,(当然题目中要求m != 0,这里只是做个假设)可以得到一分。
若 n % k == 0,将数组分成了k段
则原数组中m 必须为 abs(h[ i ] - h[ i + k])的因数.

在这里插入图片描述

代码

#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n;
int h[N];

int gcd(int a, int b)  // 欧几里得算法
{
    return b ? gcd(b, a % b) : a;
}


void solve()
{
    cin >> n;
    int ans = 0;
    for(int i = 1; i <= n; i ++) cin >> h[i];
    for(int i = 1; i <= n; i ++)
    {
        if(n % i == 0)
        {
            int m = 0;
            for(int k = 1; k + i <= n; k ++)
            {
                m = gcd(m,abs(h[i + k] - h[k]));
            }
            ans += (m != 1);
        }
    }
    cout << ans << endl;
}

int main()
{
    int t;
    cin >> t;
    while(t --)
        solve();
    return 0;
}

题目来自:Partitioning the Array

  • 14
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只大黄猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值