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;
}