POJ 1091 跳蚤

跳蚤

Time Limit: 1000ms
Memory Limit: 10000KB
This problem will be judged on PKU. Original ID: 1091
64-bit integer IO format: %lld      Java class name: Main
 
Z城市居住着很多只跳蚤。在Z城市周六生活频道有一个娱乐节目。一只跳蚤将被请上一个高空钢丝的正中央。钢丝很长,可以看作是无限长。节目主持人会给该跳蚤发一张卡片。卡片上写有N+1个自然数。其中最后一个是M,而前N个数都不超过M,卡片上允许有相同的数字。跳蚤每次可以从卡片上任意选择一个自然数S,然后向左,或向右跳S个单位长度。而他最终的任务是跳到距离他左边一个单位长度的地方,并捡起位于那里的礼物。 
比如当N=2,M=18时,持有卡片(10, 15, 18)的跳蚤,就可以完成任务:他可以先向左跳10个单位长度,然后再连向左跳3次,每次15个单位长度,最后再向右连跳3次,每次18个单位长度。而持有卡片(12, 15, 18)的跳蚤,则怎么也不可能跳到距他左边一个单位长度的地方。 
当确定N和M后,显然一共有M^N张不同的卡片。现在的问题是,在这所有的卡片中,有多少张可以完成任务。 
 

Input

两个整数N和M(N <= 15 , M <= 100000000)。
 

Output

可以完成任务的卡片数。
 

Sample Input

2 4

Sample Output

12

Hint

这12张卡片分别是: 
(1, 1, 4), (1, 2, 4), (1, 3, 4), (1, 4, 4), (2, 1, 4), (2, 3, 4), 
(3, 1, 4), (3, 2, 4), (3, 3, 4), (3, 4, 4), (4, 1, 4), (4, 3, 4) 
 

Source

 
解题:容斥原理,先找出n个与m不互质的,然后减去就是了
有扩展欧几里得的影子
 1 #include <iostream>
 2 using namespace std;
 3 typedef long long LL;
 4 const int maxn = 50;
 5 LL p[maxn],n,m,ret,tot;
 6 LL quickPow(LL base,LL index){
 7     LL ret = 1;
 8     while(index){
 9         if(index&1) ret *= base;
10         index >>= 1;
11         base *= base;
12     }
13     return ret;
14 }
15 void init(LL x){
16     tot = 0;
17     for(int i = 2; i*i <= x; ++i){
18         if(x%i == 0){
19             p[tot++] = i;
20             while(x%i == 0) x /= i;
21         }
22     }
23     if(x > 1) p[tot++] = x;
24 }
25 int main(){
26     ios::sync_with_stdio(false);
27     while(cin>>n>>m){
28         init(m);
29         for(int i = 1; i < (1<<tot); ++i){
30             int cnt = 0;
31             LL tmp = 1;
32             for(int j = 0; j < tot; ++j){
33                 if((i>>j)&1){
34                     cnt++;
35                     tmp *= p[j];
36                 }
37             }
38             if(cnt&1) ret += quickPow(m/tmp,n);
39             else ret -= quickPow(m/tmp,n);
40         }
41         cout<<(quickPow(m,n) - ret)<<endl;
42     }
43     return 0;
44 }
View Code

 

posted @ 2015-10-01 10:02  狂徒归来  阅读(247)  评论(0编辑  收藏  举报