URAL 1139. City Blocks (数论)

来源:互联网 发布:js 判断是否为整数 编辑:程序博客网 时间:2024/05/01 16:29

1139. City Blocks

Time limit: 1.0 second
Memory limit: 64 MB
The blocks in the city of Fishburg are of square form.N avenues running south to north and M streets running east to west bound them. A helicopter took off in the most southwestern crossroads and flew along the straight line to the most northeastern crossroads. How many blocks did it fly above?
Note. A block is a square of minimum area (without its borders).

Input

The input contains N and M separated by one or more spaces.1 <N, M < 32000.

Output

The number of blocks the helicopter flew above.

Samples

inputoutput
4 3
4
3 3
2

Notes

The figures for samples:
Problem illustration
Problem Source: Quarterfinal, Central region of Russia, Rybinsk, October 17-18 2001




解析:先令n = n - 1, m = m - 1:

考虑n或m只有1的情况,不妨设m = 1,那么图形就变成了一个n个小正方体拼在一起的长方体,显然答案为n,因为灰机穿过了n个街区,我们可以认为,每穿过一条竖线,就会多穿过一个街区(包括第一条竖线,不包括最后一条竖线)。
那么当n, m>1的时候,也是每穿过一条竖线,多穿过一个街区,每穿过一条横线,多穿过一个街区。但是答案却不是n + m。
因为当灰机穿过一个整点(横纵坐标均为整数)的时候,同时穿过横线和竖线,多穿过的街区是一样的。
对于灰机的路线来讲,穿过的整点数为gcd(n, m)(不算最后一个)
第一个穿过的整点为(1,1),第二个为(n / gcd, m / gcd),第三个为(n / gcd * 2, m / gcd * 2)……最后一个为(n / gcd * (gcd - 1), m / gcd * (gcd - 1))。一共gcd个。这里的gcd为gcd(n, m)。
于是,n + m减掉穿过整点的时候重复加上的街区,则答案为n + m - gcd(n, m)。




AC代码:

#include <bits/stdc++.h>using namespace std;int main(){    int n, m;    while(scanf("%d%d", &n, &m) != EOF){        n --; m --;        printf("%d\n", n + m - __gcd(n, m));     //__gcd(n, m)是algorithm头文件里的库函数    }    return 0;}



0 0
原创粉丝点击