Problem A: City
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
题目描述
Hi ICPCer, welcome to Xi’an.
Being a beautiful ancient city, Xi’an is the capital city of Zhou, Qin, Han, and Tang Dynasties. With a long history, the streets in Xi’an have a grid pattern.
Attracted by the streets’ structure, Coach Pang would like to conduct his research on them. He draws an n×m grid on the board. The grid consists {n+1}n+1 vertical line segments and {m+1}m+1 horizontal line segments. The vertical and horizontal line segments intersect at exactly (n+1)×(m+1) points, forming n×m unit squares. We call the (n+1)×(m+1) intersections grid points. Output the number of line segments(not only vertical or horizontal) l satisfying the following three conditions:
1.The length is not zero.
2.Both endpoints of l are grid points.
3.The midpoint of l is a grid point.
中文翻译
你好 ICPCer,欢迎来到西安。
西安是一座美丽的古城,是周、秦、汉、唐的都城。西安历史悠久,街道呈网格状。
庞教练被街道的结构所吸引,想对街道进行研究。他在黑板上画了一个n×m的网格。网格由{n+1}n+1条垂直线段和{m+1}m+1条水平线段组成。垂直线段和水平线段正好在(n+1)×(m+1)点相交,形成n×m单位正方形。我们称之为(n+1)×(m+1)交点网格点。输出满足以下三个条件的线段数(不仅是垂直线段或水平线段)l:
1.长度不为零。
2.l 的两个端点都是网格点。
3.l 的中点是网格点。
输入描述:
The only line contains two integers n,m(1≤n,m≤1000).
输出描述:
Print the answer in a single line.
示例1
输入
1 1
输出
0
示例2
输入
2 3
输出
14
分析
- 乍一看是一个数学题,仔细一看还真是 ヾ(≧▽≦*)o
- 由于题目要求 l 的两个端点都是网格点,因此每条竖直或水平的直线拆分成的 k 段每段必须含有偶数个小段
- 观察水平和竖直的切分情况找规律可以发现:
- n=3,k=2 n=4,k=3+1=4 n=5,k=4+2=6 n=6,k=5+3+1=9
- 总结规律:k=(n-1)+(n-3)+…
- 把一行拆成 k1 个符合要求的小段,拆出来的 k1 段再乘上 n+1 行
- 列也如此处理,拆成 k2 个小段,拆出来的 k2 段再乘上 m+1 列
- 再处理一下对角线,满足条件的方格长和宽分别有刚才的 k1 k2 种拆法
- 因此满足条件的方格数为 k1 × k2 个,每个有 2 条对角线
- 最终答案即为 k1 × (n+1) + k2 × (m+1) + k1 × k2 × 2
- 以第二个样例为例绘制一张图便于理解
代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
long long n,m,ln=0,lm=0,tmp,ans=0;
cin>>n>>m;
tmp=n-1;
while(tmp>0)
{
ln+=tmp;
tmp-=2;
}
tmp=m-1;
while(tmp>0)
{
lm+=tmp;
tmp-=2;
}
ans=ln*(m+1)+lm*(n+1);
ans+=2*lm*ln;
cout<<ans;
return 0;
}