zoukankan      html  css  js  c++  java
  • HDU 2841-Visible Trees 【容斥】

    <题目链接>

    题目大意:

    有一个农民,站在(0,0)点,从(1,1)点到(m,n)点每个点上有棵树,问这个农民能看到多少棵树。(如果多棵树在同一条直线上,那么他只能看到一颗)

    解题分析:

    因为农民站在(0,0)点,所以,我们根据图像分析可得,设树的坐标为(x,y),当gcd(x,y)=1,即树的横、纵坐标互质时,该树能被农民看到。于是本题直接在区间 [1,n]中枚举x ,然后求区间 [1,m] 中与x互质的数的个数。就是在最基础的模型上加上枚举操作。

     1 #include <cstdio>
     2 #include <cstring>
     3 #include <iostream>
     4 #include <algorithm>
     5 #include <vector>
     6 using namespace std;
     7 
     8 typedef long long ll;
     9 vector<int>vec;
    10 int n,m;
    11 template<typename T>    
    12 inline T read(T&x){
    13     x=0;int f=0;char ch=getchar();
    14     while (ch<'0' || ch>'9') f|=(ch=='-'),ch=getchar();
    15     while (ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
    16     return x=f?-x:x;
    17 }
    18 void pfactor(int x){     //求出x的所有质因子
    19     vec.clear();
    20     for(int i=2;i*i<=x;i++) if(x%i==0){
    21         vec.push_back(i);
    22         while(x%i==0)x/=i;
    23     }
    24     if(x>1)vec.push_back(x);
    25 }
    26 int solve(int x){     //求[1,x]中,与枚举的i不互质的数的个数
    27     int sum=0;
    28     for(int i=1;i<(1<<vec.size());i++){
    29         int res=1,cnt=0;
    30         for(int j=0;j<vec.size();j++){
    31             if(i & (1<<j)){
    32                 res*=vec[j];
    33                 cnt++;
    34             }
    35         }
    36         if(cnt & 1)sum+=x/res;
    37         else sum-=x/res;
    38     }
    39     return sum;
    40 }
    41 int main(){
    42     int T;cin>>T;while(T--){
    43         read(n);read(m);
    44         ll ans=m;      //因为第一行为1,一定与[1,m]全部互质
    45         for(int i=2;i<=n;i++){    //直接从第二行开始
    46             pfactor(i);       //因为是求[1,m]中与i互质的数的个数,所以这里是求i得质因子,不要弄混
    47             ans+=m-solve(m);   
    48         }
    49         printf("%lld
    ",ans);
    50     }
    51 }

    2019-02-10

  • 相关阅读:
    团队冲刺第五天
    每日学习
    团队冲刺第四天
    团队冲刺第三天
    每日学习
    2021.4.12
    2021.4.10
    2021.3.18
    2021.3.15
    2021.3.14
  • 原文地址:https://www.cnblogs.com/00isok/p/10358598.html
Copyright © 2011-2022 走看看