Frogs HDU - 5514 —— 青蛙跳环,容斥

There are m stones lying on a circle, and n frogs are jumping over them.
The stones are numbered from 0 to m−1 and the frogs are numbered from 1 to n. The i-th frog can jump over exactly ai stones in a single step, which means from stone j mod m to stone (j+ai) mod m (since all stones lie on a circle).

All frogs start their jump at stone 0, then each of them can jump as many steps as he wants. A frog will occupy a stone when he reach it, and he will keep jumping to occupy as much stones as possible. A stone is still considered ``occupied" after a frog jumped away.
They would like to know which stones can be occupied by at least one of them. Since there may be too many stones, the frogs only want to know the sum of those stones’ identifiers.
Input
There are multiple test cases (no more than 20), and the first line contains an integer t,
meaning the total number of test cases.

For each test case, the first line contains two positive integer n and m - the number of frogs and stones respectively (1≤n≤104, 1≤m≤109).

The second line contains n integers a1,a2,⋯,an, where ai denotes step length of the i-th frog (1≤ai≤109).
Output
For each test case, you should print first the identifier of the test case and then the sum of all occupied stones’ identifiers.
Sample Input
3
2 12
9 10
3 60
22 33 66
9 96
81 40 48 32 64 16 96 42 72
Sample Output
Case #1: 42
Case #2: 1170
Case #3: 1872

题意:

n个青蛙跳围成1圈的m个石子,石子编号从0开始到m-1,接下来给你n个青蛙跳的距离,青蛙可以跳无限次,问你最终被跳到的石子编号和是多少。

题解:

我们可以知道一个数跳过的所有点是gcd(m,k)的倍数,那么我们只需要求出所有m的因子,再看看每个因子是不是输入数与m的gcd的倍数,最后对每个因子都做一遍,再加上容斥。

#include<bits/stdc++.h>
using namespace std;
#define eps 1e-6
#define ll long long
int yz[1005],ctyz;
int vis[50005],num[50005],a[10005];
int main()
{
    int t;
    scanf("%d",&t);
    int cas=0;
    while(t--)
    {
        int n,m;
        scanf("%d%d",&n,&m);
        ctyz=0;
        memset(vis,0,sizeof(vis));
        memset(num,0,sizeof(num));
        for(int i=1;i<=sqrt(m)+eps;i++)
        {
            if(m%i==0)
            {
                yz[++ctyz]=i;
                if(i*i!=m)
                    yz[++ctyz]=m/i;
            }
        }
        sort(yz+1,yz+ctyz+1);
        for(int i=1;i<=n;i++)
        {
            int x,g;
            scanf("%d",&x);
            g=__gcd(x,m);
            for(int j=1;j<=ctyz;j++)
                if(yz[j]%g==0)
                    vis[j]=1;
        }
        ll ans=0;
        for(int i=1;i<=ctyz;i++)
        {
            if(vis[i]!=num[i])
            {
                ll tim=(ll)(m-1)/yz[i];
                ans+=(ll)yz[i]*tim*(tim+1)/2*(vis[i]-num[i]);
                int dec=vis[i]-num[i];
                for(int j=i;j<=ctyz;j++)
                    if(yz[j]%yz[i]==0)
                        num[j]+=dec;
            }
        }
        printf("Case #%d: %lld\n",++cas,ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tianyizhicheng/article/details/83216392
今日推荐