Visible Trees + 数论,互质和容斥原理

来源:互联网 发布:网络层 ip层 编辑:程序博客网 时间:2024/06/08 20:11

Visible Trees

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


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
21 12 3
 

Sample Output
15
#include<iostream>#include <stdio.h>#include <string.h>#include <stdlib.h>using namespace std ;__int64  count[100005],num[100005][20];__int64  prim[100005];void init(){    int i,j;    memset(prim,0,sizeof(prim));    memset(count,0,sizeof(count));    for(i=2;i<=100000;i++)    if(prim[i]==0)    {      num[i][0]=i;      count[i]++;      for(j=2;j*i<=100000;j++)      {         int m=i*j;         prim[m]=1;         num[m][count[m]]=i;         count[m]++;      }    }}__int64  not_prim(int n,int m,int k){    int i,j;    __int64 ans=0;    if(n==1) return 0;    for (i=k; i<count[n]; i++)    {        ans += m/num[n][i] - not_prim(n,m/num[n][i],i+1);    }    return ans;}int main(){    int T,i,j,m,n;    init(); //求100000之内的质数    while (scanf("%d",&T)!=EOF)    {        while (T--)        {            scanf("%d%d",&n,&m);            if(n<m)            {                int t=n;                n=m;                m=t;            }            __int64  ans = n;            for (i=2; i<=m; i++)            {                ans+=n-not_prim(i,n,0);            }            printf("%I64d\n",ans);        }    }}


原创粉丝点击