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

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

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+1;
int isprime[maxn];
vector<int>p[maxn];
void prime(int n)
{
    for(int i=2;i<n;++i)
    {
        if(!isprime[i])
        {
            p[i].push_back(i);
            for(int j=2*i;j<n;j+=i)
            p[j].push_back(i),isprime[j]=1;
        }
    }
}
int slove(int x,int y)
{
    int len=p[x].size(),ans=0;
    for(int i=1;i<(1LL<<len);++i)
    {
        int num=0,res=1;
        for(int j=0;j<len;++j)
        {
            if(i&(1LL<<j)) num++,res*=p[x][j];
        }
        if(num&1) ans+=y/res;
        else ans-=y/res;
    }
    return y-ans;
}
int main()
{
    int n,m,T;
    prime(maxn);
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d %d",&n,&m);
        if(n>m) swap(n,m);
        ll ans=m;
        for(int i=2;i<=n;++i)
        ans+=slove(i,m);
        printf("%lld\n",ans);
    }
}
发布了328 篇原创文章 · 获赞 1 · 访问量 9117

猜你喜欢

转载自blog.csdn.net/qq_42479630/article/details/105168675