hdu2841 Visible Trees 容斥原理

本文介绍了一个基于容斥原理的问题:在一个m*n的网格中计算农民Sherlock能看见多少树木。当三棵树在一条直线上时,只能看见最近的一棵。通过预处理质因数分解和初始化相关数据结构,利用容斥原理高效地解决了该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

转载于:https://www.cnblogs.com/cenariusxz/p/6592520.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值