分析: a[i] 能到达的点为 gcd(a[i],m) 的倍数。预处理出所有 gcd ,两个不同 a[i] 能同时到的点为 lcm(gcd(a[i],m),gcd(a[j],m)) 的倍数,容斥写,当遇到当前值是这个 gcd(a[i],m) 的倍数是,那么就不用算这个。
具体复杂度我也不会算。
代码:
#include <bits/stdc++.h>
#define LL long long
#define FOR(i,x,y) for(int i = x;i < y;++ i)
#define IFOR(i,x,y) for(int i = x;i > y;-- i)
using namespace std;
const int maxn = 10010;
typedef vector <int> VT;
int a[maxn],g[maxn];
int gcd(int a,int b){
return b == 0 ? a : gcd(b,a%b);
}
int n,m;
VT s;
void init(){
scanf("%d%d",&n,&m);
s.clear();
FOR(i,0,n){
scanf("%d",&a[i]);
s.push_back(gcd(a[i],m));
}
sort(s.begin(),s.end());
VT :: iterator it = unique(s.begin(),s.end());
s.erase(it,s.end());
n = (int)s.size();
FOR(i,0,n) g[i] = s[i];
}
LL ans;
void dfs(int wei,int num,int sz){
if(wei == n){
if(sz){
LL last = (m-1)/num;
LL tem = (last+1)*last*num/2;
if(sz%2) ans += tem;
else ans -= tem;
}
return;
}
if(num % g[wei] == 0) return;
dfs(wei+1,num,sz);
LL lcm = (LL)num*g[wei]/(LL)gcd(num,g[wei]);
if(lcm < (LL)m) dfs(wei+1,lcm,sz+1);
}
void work(){
ans = 0;
if(g[0] == 1){
ans = (LL)m*(m-1)/2;
}
else dfs(0,1,0);
printf("%I64d\n",ans);
}
int main()
{
//freopen("test.in","r",stdin);
int T,tCase = 0; scanf("%d",&T);
while(T--){
printf("Case #%d: ",++tCase);
init();
work();
}
return 0;
}