HDU2841 Visible Trees(容斥原理,二维)

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

2
1 1
2 3

Sample Output

1
5

思路

题目转化一下就可以变成:已知 x[1,n] x ∈ [ 1 , n ] , y[1,m] y ∈ [ 1 , m ] 求x和y这两个集合中互质的数的个数。

利用容斥,枚举x集合,然后暴力加起来

代码

#include <cstdio>
#include <cstring>
#include <cctype>
#include <stdlib.h>
#include <string>
#include <map>
#include <iostream>
#include <stack>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
#define inf 1000000
#define mem(a,b) memset(a,b,sizeof(a))
ll a[50],b[1010];//a保存n的质因子,a[0]表示质因子个数
void div(ll n)//分解质因数
{
    ll j=0;
    for(ll i=2; i*i<=n; i++)
        if(n%i==0)
        {
            while(n%i==0)
                n/=i;
            a[++j]=i;
        }
    if(n>1) a[++j]=n;
    a[0]=j;
}
ll get_cnt(ll mid)//1--mid之间与n互质的数有多少个
{
    ll g=0,sum=mid,t;
    b[++g]=1;
    for(ll i=1; i<=a[0]; i++)
    {
        t=g;
        for(ll j=1; j<=g; j++)
        {
            b[++t]=b[j]*a[i]*-1;
            sum+=mid/b[t];
        }
        g=t;
    }
    return sum;
}

int main()
{
    ll t,n,m;
    scanf("%lld",&t);
    while(t--)
    {
        mem(a,0);
        mem(b,0);
        ll ans=0;
        scanf("%lld%lld",&n,&m);
        for(ll i=1; i<=n; i++)
        {
            div(i);
            ans+=get_cnt(m);
        }
        printf("%lld\n",ans);
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值