hdoj 2841 Visible Trees 【容斥原理】

Visible Trees

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


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
 
 
题目翻译:给你一个(m,n)的矩阵,每个点上有一颗树,你站在(0,0)点看矩阵,前面的树会挡着后面的树,问你此时一共可以看到多少树!
结题思路:由于是站在(0,0),因此此时被挡的那棵树(X,Y)和挡它的那棵树(x,y)有一些关系,此时和(0,0)三点共线,因此X / x == Y / y;
因此(X,Y)必有公约数,因此点任意一点(A,B)只要A,B有约数,则一定看不到,反之,A,B互质则一定可以看到,因此问题转化为求图中的互质点对;
 
 
 
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
int p[100],k;
void getp(int n)
{
    int i;
    k=0;
    for(i=2;i*i<=n;i++)
    {
        if(n%i==0)
        p[k++]=i;
        while(n%i==0)
        n/=i;
    }
    if(n>1) p[k++]=n;
}
int nop(int m)
{
    int i,j;
    int t,top=0,sum;
    int que[10000+100];
    que[top++]=-1;
    for(i=0;i<k;i++)
    {
        t=top;
        for(j=0;j<t;j++)
        {
            que[top++]=que[j]*p[i]*(-1);
        }
    }
    for(i=1,sum=0;i<top;i++)
    sum+=m/que[i];
    return sum;
}
int main()
{
    int t,n,m;
    int i;
    long long ans;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        ans=n;
        for(i=2;i<=m;i++)
        {
            getp(i);
            ans+=n-nop(n);
        }
        printf("%lld\n",ans);
    }
    return 0;
}

另一种思路:预处理素数表(看的别人的)
 
 
 
#include<cstdio>
#define LL long long
int prime[100005][20];
int cnt[100005]={0};
void Init()
{
    for(int i=2;i<=100000;i++)
    {
        if(cnt[i]) continue;
        prime[i][0]=i;
        cnt[i]=1;
        for(int j=2;j*i<=100000;j++)
            prime[i*j][cnt[i*j]++]=i;
    }
}
LL dfs(int m,int n,int idx)
{
    LL ret=0;
    for(int i=idx;i<cnt[m];i++)
        ret+=n/prime[m][i]-dfs(m,n/prime[m][i],i+1);
    return ret;
}
int main()
{
    Init();
    int t,n,m;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        LL ans=n;
        for(int i=2;i<=m;i++)
            ans+=(n-dfs(i,n,0));
        printf("%I64d\n",ans);
    }
    return 0;
}

 

你可能感兴趣的:(hdoj 2841 Visible Trees 【容斥原理】)