There are many trees forming a m * n grid, the grid starts from (1,1). Farmer Sherlock is standing at (0,0) point. He wonders how many trees he can see.

If two trees and Sherlock are in one line, Farmer Sherlock can only see the tree nearest to him.

容斥原理裸题

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 #include<math.h>
 5 using namespace std;
 6 typedef long long ll;
 7 
 8 const int maxn=1e5+5;
 9 
10 int pnum[maxn],good[maxn];
11 
12 void init(){
13     memset(pnum,0,sizeof(pnum));
14     memset(good,0,sizeof(good));
15     for(int i=2;i<=100000;++i){
16         if(!pnum[i]){
17             pnum[i]=1;
18             for(int j=2;i*j<=100000;++j){
19                 if(!(j%i))good[i*j]=1;
20                 else pnum[i*j]++;
21             }
22         }
23     }
24 }
25 
26 int main(){
27     init();
28     int T;
29     scanf("%d",&T);
30     while(T--){
31         int n,m;
32         scanf("%d%d",&n,&m);
33         if(n>m)swap(n,m);
34         ll ans=0;
35         for(int i=2;i<=n;++i){
36             if(!good[i]){
37                 if(pnum[i]%2)ans+=(n/i)*((ll)m/i);
38                 else ans-=(n/i)*((ll)m/i);
39             }
40         }
41         printf("%lld\n",n*(ll)m-ans);
42     }
43     return 0;
44 }
View Code