uva1393 - Highways

本文讨论了如何计算在Hackerland国家中,为了实现任意城市之间的直接连接,需要建造多少条额外的高速公路。通过分析现有道路系统,作者提出了一种算法来确定所需高速公路的数量。

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

Hackerland is a happy democratic country with m×n cities, arranged in a rectangular m by n grid and connected by m roads in the east-west direction and n roads in the north-south direction. By public demand, this orthogonal road system is to be supplemented by a system of highways in sucha way that there will be a direct connection between any pair of cities. Each highway is a straight line going through two or more cities. If two cities lie on the same highway, then they are directly connected.If two cities are in the same row or column, then they are already connected by the existing orthogonal road system (each east-west road connects all the m cities in that row and each north-south road connects all the n cities in that column), thus no new highway is needed to connect them. Your task is to count the number of highway that has to be built (a highway that goes through several cities on a straight line is counted as a single highway).

\epsfbox{p3720.eps}

Input 

The input contains several blocks of test cases. Each test case consists of a single line containing two integers 1$ \le$n, m$ \le$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 be built.

Sample Input 

2 4
3 3
0 0

Sample Output 

12
14

  N*M的点中除了水平和竖直的线有多少条。

  设左上角为(1,1),先算出每个点到它左上方有多少个向量连到一个点不经过其它点,也就转化成1-i,1-j有多少个互质对数。还有一个问题就是可能从(i,j)往左上角的向量的终点,那个终点也可以以同样的向量作为起点,这条线就已经算过了,比如(3,3)到(2,2)有一条,但是和(2,2)到(1,1)是同一条。这种情况就要减去,可以发现(i/2,j/2)这个点出发的向量,在(i,j)出发的这些向量上对应的直线都已经计算过,所以要减去。最后要乘以2是因为直线朝右上方向跟朝左上方向是完全对称的。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cstdlib>
#include<cmath>
#define INF 0x3f3f3f3f
#define MAXN 310
#define MAXM 20010
#define MAXNODE 4*MAXN
#define MOD 1000000000
#define eps 1e-9
using namespace std;
int N,M;
long long cnt[MAXN][MAXN],sum[MAXN][MAXN];
int gcd(int a,int b){
    return a%b?gcd(b,a%b):b;
}
void init(){
    memset(cnt,0,sizeof(cnt));
    memset(sum,0,sizeof(sum));
    for(int i=1;i<MAXN;i++)
        for(int j=1;j<MAXN;j++) cnt[i][j]=cnt[i-1][j]+cnt[i][j-1]-cnt[i-1][j-1]+(gcd(i,j)==1?1:0);
    for(int i=1;i<MAXN;i++)
        for(int j=1;j<MAXN;j++) sum[i][j]=sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+cnt[i][j]-cnt[i/2][j/2];
}
int main(){
    //freopen("in.txt", "r", stdin);
    init();
    while(scanf("%d%d",&N,&M),N||M){
        printf("%lld\n",2*sum[N-1][M-1]);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值