Hackerland is a happy democratic country with m×n cities, arranged in a rectangular m by n grid andconnected by m roads in the east-west direction and n roads in the north-south direction. By publicdemand, this orthogonal road system is to be supplemented by a system of highways in sucha waythat there will be a direct connection between any pair of cities. Each highway is a straight line goingthrough two or more cities. If two cities lie on the same highway, then they are directly connected.If twocities are in the same row or column, then they are already connected by the existing orthogonal roadsystem (each east-west road connects all the m cities in that row and each north-south road connectsall the n cities in that column), thus no new highway is needed to connect them. Your task is to countthe number of highway that has to be built (a highway that goes through several cities on a straightline is counted as a single highway).
Input
The input contains several blocks of test cases. Each test case consists of a single line containing twointegers 1 ≤ n, m ≤ 300, specifying the number of cities. The input is terminated by a test case with n = m = 0.
Output
For each test case, output one line containing a single integer, the number of highways that must bebuilt.
Sample Input
2 4
3 3
0 0
Sample Output
12
14
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
神奇容斥原理~
有一个n行m列的点阵,问有多少条非水平非竖直的直线至少经过两个点。
相当于是求不同形状的长方形有多少个,然后再乘2。
枚举x和y互质的点,然后减去里面形状相同的长方形数。
m和n要减一,结果要乘二~
#include<cstdio>
#include<iostream>
using namespace std;
int n,m,tot,a[301][301],ans;
int gcd(int u,int v)
{
if(a[u][v]) return a[u][v];
return v ? gcd(v,u%v):u;
}
int main()
{
for(int i=1;i<=300;i++)
for(int j=i;j<=300;j++) a[i][j]=a[j][i]=gcd(i,j);
while(scanf("%d%d",&n,&m)==2 && n)
{
ans=0;n--;m--;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(a[i][j]==1) ans+=(n-i+1)*(m-j+1)-max(0,n-2*i+1)*max(0,m-2*j+1);
printf("%d\n",ans*2);
}
return 0;
}