hdu2841 Visible Trees(容斥)

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
2
1 1
2 3
Sample Output
1
5

该题目怎么分析呢?

我们最终可以得出是和行数互质的情况会被保留,为什么?

我们来举个例子:

(2,3)

(6,9)

(2,3)互质,在第二行第三列

(6,9)不互质,在第六行第九列

由于你人站在(0,0)在同一直线上的点只能看见一个,所以(6,9)被(2,3)挡住了

所以不互质的点都被互质的点挡住了

代码:

#include <iostream>
using namespace std;
typedef long long ll;
const ll maxn=100000+10;
ll prime[maxn];
ll fac[maxn];
//表示和n互质的范围为(1~x)的有多少个 
ll solve(ll n,ll m)
{
    ll num=0;
    ll temp_n=n;
    for(ll i=2;i*i<=n;i++){
        if(temp_n%i==0){
            prime[num++]=i;
            while(temp_n%i==0){
                temp_n/=i;
            } 
        }
    }
    if(temp_n!=1)prime[num++]=temp_n;
    ll cnt=0;
    fac[cnt++]=1;
    for(ll i=0;i<num;i++){
        ll temp_cnt=cnt;
        for(ll j=0;j<temp_cnt;j++)
            fac[cnt++]=fac[j]*prime[i]*-1;
    }
    ll ans=0;
    for(ll i=0;i<cnt;i++){
        ans+=m/fac[i];
    }
    return ans;
}
int main()
{
    
    ll T;
    cin>>T;
    while(T--){
        ll m,n;
        cin>>m>>n;
        ll ans=n;
        for(ll i=2;i<=m;i++){
            ans+=solve(i,n);
//            cout<<i<<"  "<<solve(i,n)<<endl;
        }
        cout<<ans<<endl; 
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jamence

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值