hdu5514 Frogs(容斥原理)

题目链接
Problem Description
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

Source
2015ACM/ICPC亚洲区沈阳站-重现赛(感谢东北大学)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e4+1;
int num[maxn];
vector<int>v;
int main()
{
    int T,n,m,t;
    scanf("%d",&T);
    for(int s=1;s<=T;++s)
    {
        v.clear();
        int flag=0;
        scanf("%d %d",&n,&m);
        for(int i=0;i<maxn;++i) num[i]=0;
        for(int i=1;i*i<=m;++i)//存m的因子 
        if(m%i==0){
            v.push_back(i);
            if(i!=m/i) v.push_back(m/i);
        }
        sort(v.begin(),v.end());
        for(int i=1;i<=n;++i)
        {
            scanf("%d",&t);
            t=__gcd(t,m);
            if(t==1)flag=1;
            for(int j=0;j<v.size();++j)
            if(v[j]%t==0) num[j]=1;
         } 
         printf("Case #%d: ",s);
         if(flag){
             printf("%lld\n",1LL*m*(m-1)/2);continue;
         }
         ll ans=0;
         for(int i=0;i<v.size();++i)
         {
             if(num[i]==0) continue;
             ans+=1LL*(m/v[i]-1)*m/2*num[i];//算每个因子的贡献 
             for(int j=i+1;j<v.size();++j)//如果m的因子当中有g【i】的倍数的话要把它删去 
             if(v[j]%v[i]==0) num[j]-=num[i];
         }
         printf("%lld\n",ans);
    }
}
发布了328 篇原创文章 · 获赞 1 · 访问量 9115

猜你喜欢

转载自blog.csdn.net/qq_42479630/article/details/105168832