hdu2841(容斥原理)

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.

题意:

在m*n的方格中,每个里面有一棵树(从(1,1)到(m,n)),你在(0,0),问可以看到几棵树

解题思路:

很明显,第一排和第一列都可以看到,那么后面的呢。。。。。我也是看了别人的博客才知道,如果一个一棵树的坐标(x,y),

x,y互质,则可以看到,所以题目就是求,有多少对坐标是互质的。

枚举第一行的每一个元素,看所在的列有多少个数与之互质,全都加起来即可

所以问题又变为了,在区间1~n之间,有多少个数与x互质,(欧拉函数是1~n之间与n互质的个数),so这里就用容斥定理解决

容斥定理的模板和简单介绍:https://blog.csdn.net/qq_40733911/article/details/81705233

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
int fac[100000];
int div(int n)
{
    int cnt=0;
    for(int i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            fac[cnt++]=i;
            while(n%i==0) n/=i;
        }
    }
    if(n>1) fac[cnt++]=n;
    return cnt;
}
int solve(int n,int cnt)
{
    int ans=0;
    for(int i=1;i< (1<<cnt);i++)
    {
        int ones=0,mult=1;
        for(int j=0;j<cnt;j++)
        {
            if(i & (1<<j))
            {
                ones++;
                mult*=fac[j];
            }
        }
        if(ones &1)
            ans+= n/mult;
        else
            ans-= n/mult;
    }
    return n-ans;
}
int main()
{
   int t;
   cin>>t;
   while(t--)
   {
       int n,m;
       ll ans=0;
       cin>>n>>m;
       for(int i=1;i<=n;i++)
       {
           int cnt=div(i);
           ans+= solve(m,cnt);
       }
       cout<<ans<<endl;
   }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值