hdu 2841 Visible Trees 容斥,分解质因数

Visible Trees

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2697 Accepted Submission(s): 1173

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

Source
2009 Multi-University Training Contest 3 - Host by WHU


题意:

给出一个n*m的格子,每个格子里种有一棵树,让你站在格子外的(0,0)处,问你能看到多少棵树(前面的树会被后面的遮住)?(1<=n,m<=1e5)


解:

分析一下会发现,就是需要统计 [1,n] 内的 x [1,m]内的 y ,使得有序对<x,y>满足 (x,y)=1
n<m ,对于 y0[1,m] ,满足条件的 x 数目=phi(y0)
根据y的取值,令 ans=f[1,m]+f[m+1,n]
所以 f[1,m]=mi=1phi(i)
对于f[m+1,n],对于所有 y0 ,分解质因数,再用容斥原理,可以算出 (x0,y0)!=1 x0 数量 num ,再用m减去 num 即可。


代码:


#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;

#define all(x) (x).begin(), (x).end()
#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)
#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)
#define mes(a,x,s)  memset(a,x,(s)*sizeof a[0])
#define mem(a,x)  memset(a,x,sizeof a)
#define ysk(x)  (1<<(x))
typedef long long ll;
typedef pair<int, int> pii;
const int INF =0x3f3f3f3f;
const int maxn= 100000   ;
int prime[maxn+10][20],e[maxn+5],a,b;
ll sum[maxn+10],ret;
void pre()
{
    e[1]=1;
    for(int i=2;i<=maxn;i++)  if(!e[i]    ) {
        for(int j=i;j<=maxn;j+=i)  {
            if(!e[j]  )  e[j]=j;
            e[j]=e[j]/i*(i-1);
            int& num=prime[j][0];
            prime[j][++num]=i;
        }

    }
    sum[1]=1;
    for(int i=2;i<=maxn;i++)  sum[i]=sum[i-1]+e[i];
}

void dfs(int ind,int x,int mul,int tag)
{
    if(ind== prime[x][0]+1)  return;
    dfs(ind+1,x,mul,tag);
    int g=__gcd(mul,prime[x][ind]);
    mul=  mul/g*prime[x][ind];
    ret+=a/mul*tag;
    dfs(ind+1,x,mul,-tag );
}
int main()
{
   pre();
   std::ios::sync_with_stdio(false);
   int T;cin>>T;
   while(T--)
   {
       cin>>a>>b;
       if(a>b) swap(a,b);
       ll ans=2*sum[a]-1;
       for(int i=a+1;i<=b;i++)
       {
           ret=0;
           dfs( 1,i,1, 1  );
           ans+= a-ret;
       }
       cout<<ans<<endl;

   }
   return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值