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
和
令
n<m
,对于
y0∈[1,m]
,满足条件的
x
数目
根据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;
}