hdu 2841 Visible Trees 容斥,分解质因数

来源:互联网 发布:linux认证工程师 编辑:程序博客网 时间:2024/06/04 19:50

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[1,m]内的y,使得有序对<x,y>满足(x,y)=1
n<m,对于y0[1,m],满足条件的x数目=phi(y0)
根据y的取值,令ans=f[1,m]+f[m+1,n]
所以f[1,m]=mi=1phi(i)
对于f[m+1,n],对于所有y0,分解质因数,再用容斥原理,可以算出(x0,y0)!=1x0数量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;}
0 0
原创粉丝点击