容斥原理

hdoj 2841 Visible Trees 【容斥原理】

原创 2015年04月30日 22:01:32
  • 519

Visible Trees

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1767    Accepted Submission(s): 724


Problem Description
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.

Input
The first line contains one integer t, represents the number of test cases. Then there are multiple test cases. For each test case there is one line containing two integers m and n(1 ≤ m, n ≤ 100000)

Output
For each test case output one line represents the number of trees Farmer Sherlock can see.

Sample Input
 
   
21 12 3
Sample Output
 
   
15
 
 
题目翻译:给你一个(m,n)的矩阵,每个点上有一颗树,你站在(0,0)点看矩阵,前面的树会挡着后面的树,问你此时一共可以看到多少树!
结题思路:由于是站在(0,0),因此此时被挡的那棵树(X,Y)和挡它的那棵树(x,y)有一些关系,此时和(0,0)三点共线,因此X / x == Y / y;
因此(X,Y)必有公约数,因此点任意一点(A,B)只要A,B有约数,则一定看不到,反之,A,B互质则一定可以看到,因此问题转化为求图中的互质点对;
 
 对于每一个x,y从1~n,就转化成了求区间内与某个数互质的数的个数了.
 
  1. #include<stdio.h>  
  2. #include<string.h>  
  3. #include<math.h>  
  4. #include<stdlib.h>  
  5. #include<queue>  
  6. #include<stack>  
  7. #include<algorithm>  
  8. using namespace std;  
  9. int p[100],k;  
  10. void getp(int n)  
  11. {  
  12.     int i;  
  13.     k=0;  
  14.     for(i=2;i*i<=n;i++)  
  15.     {  
  16.         if(n%i==0)  
  17.         p[k++]=i;  
  18.         while(n%i==0)  
  19.         n/=i;  
  20.     }  
  21.     if(n>1) p[k++]=n;  
  22. }  
  23. int nop(int m)  
  24. {  
  25.     int i,j;  
  26.     int t,top=0,sum;  
  27.     int que[10000+100];  
  28.     que[top++]=-1;  
  29.     for(i=0;i<k;i++)  
  30.     {  
  31.         t=top;  
  32.         for(j=0;j<t;j++)  
  33.         {  
  34.             que[top++]=que[j]*p[i]*(-1);  
  35.         }  
  36.     }  
  37.     for(i=1,sum=0;i<top;i++)  
  38.     sum+=m/que[i];  
  39.     return sum;  
  40. }  
  41. int main()  
  42. {  
  43.     int t,n,m;  
  44.     int i;  
  45.     long long ans;  
  46.     scanf("%d",&t);  
  47.     while(t--)  
  48.     {  
  49.         scanf("%d%d",&n,&m);  
  50.         ans=n;  
  51.         for(i=2;i<=m;i++)  
  52.         {  
  53.             getp(i);  
  54.             ans+=n-nop(n);  
  55.         }  
  56.         printf("%lld\n",ans);  
  57.     }  
  58.     return 0;  
  59. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值