UVa 1393 Highways

解决在一个由m×n个城市组成的网格中,如何规划最少数量的斜向高速公路来确保任意两城市间都有直接连接的问题。利用容斥原理进行高效计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值