HDU 5514 Frogs

Frogs

Time Limit: 1000ms
Memory Limit: 65536KB
This problem will be judged on HDU. Original ID: 5514
64-bit integer IO format: %I64d      Java class name: Main

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

 
解题:容斥来一发即可
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int maxn = 10010;
 4 using LL = long long;
 5 int n,m;
 6 LL ret,a[maxn];
 7 void dfs(int pos,LL lcm,int cnt) {
 8     if(pos == n) {
 9         if(cnt) {
10             LL num = m/lcm,tmp = (((num - 1)*num)>>1)*lcm;
11             ret += (cnt&1)?tmp:-tmp;
12         }
13         return;
14     }
15     if(lcm%a[pos] == 0) return;
16     dfs(pos + 1,lcm,cnt);
17     LL LCM = lcm*a[pos]/__gcd(lcm,a[pos]);
18     if(LCM < m) dfs(pos + 1,LCM,cnt + 1);
19 }
20 int main() {
21     int kase,cs = 1;
22     scanf("%d",&kase);
23     while(kase--) {
24         scanf("%d%d",&n,&m);
25         for(int i = 0; i < n; ++i) {
26             scanf("%I64d",a + i);
27             a[i] = __gcd(a[i],static_cast<LL>(m));
28         }
29         sort(a, a + n);
30         n = unique(a,a + n) - a;
31         ret = 0;
32         if(a[0] == 1) ret = (static_cast<LL>(m)*(m-1))>>1;
33         else dfs(0,1,0);
34         printf("Case #%d: %I64d\n",cs++,ret);
35     }
36     return 0;
37 }
View Code

 

posted @ 2015-11-09 19:00  狂徒归来  阅读(293)  评论(0编辑  收藏  举报