hdu2841 Visible Trees(容斥)

来源:互联网 发布:win7引导linux 编辑:程序博客网 时间:2024/05/16 05:22

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

该题目怎么分析呢?

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

我们来举个例子:

(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;}



原创粉丝点击