您的位置:首页 > 其它

HDU 2841 Visible Trees(容斥原理,数论)

2016-04-02 17:20 429 查看


Visible Trees

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 2380 Accepted Submission(s): 989



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

Recommend

gaojie

对于i,j,若存在k>=2,且k为i,j的约数,则i,j无法观测。故使用容斥原理可求解。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>
#include<vector>
#include<string>
using namespace std;
typedef long long LL;
int m,n;
const int MAXN=100008;
int prime[MAXN];
bool vis[MAXN];
int tot;
LL ans;
int getPrime(int n){//求1~n的素数
tot=0;
memset(vis,0,sizeof(vis));
for(int i=2;i<=n;i++){
if(!vis[i]){
prime[tot++]=i;
}
for(int j=0;j<tot&&i*prime[j]<=n;j++){
vis[i*prime[j]]=true;
if(i%prime[j]==0){
break;
}
}
}
return tot;
}

void dfs(int dep,LL mul,int num){//容斥原理,dep表示使用的质数个数,mul表示乘积,num表示使用的数的编号
for(int i=num;i<tot&&prime[i]*mul<=min(m,n);i++){
LL tp=mul*prime[i];
if(dep&1){
ans+=(LL)(m/tp)*(n/tp);
}else{
ans-=(LL)(m/tp)*(n/tp);
}
dfs(dep+1,tp,i+1);
}
}
int main(){
getPrime(100000);
int t;
cin>>t;
while(~scanf("%d %d",&m,&n)){
ans=(LL)m*n;
dfs(0,1,0);
printf("%I64d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: