POJ 3090 ZOJ 2777 UVALive 3571 Visible Lattice Points(用递推比用欧拉函数更好)
来源:互联网 发布:catia v5软件下载 编辑:程序博客网 时间:2024/05/19 03:17
题目:
Description
A lattice point (x, y) in the first quadrant (x and y are integers greater than or equal to 0), other than the origin, is visible from the origin if the line from (0, 0) to (x, y) does not pass through any other lattice point. For example, the point (4, 2) is not visible since the line from the origin passes through (2, 1). The figure below shows the points (x, y) with 0 ≤ x, y ≤ 5 with lines from the origin to the visible points.
Write a program which, given a value for the size, N, computes the number of visible points (x, y) with 0 ≤ x, y ≤ N.
Input
The first line of input contains a single integer C (1 ≤ C ≤ 1000) which is the number of datasets that follow.
Each dataset consists of a single line of input containing a single integer N (1 ≤ N ≤ 1000), which is the size.
Output
For each dataset, there is to be one line of output consisting of: the dataset number starting at 1, a single space, the size, a single space and the number of visible points for that size.
Sample Input
4245231
Sample Output
1 2 52 4 133 5 214 231 32549
这个题目当然可以用欧拉函数来做,不过我更喜欢这个递推的方法。
代码:
#include<iostream>#include<stdio.h>using namespace std;int r[1001];int main(){r[1] = 1;for (int i = 2; i <= 1000; i++){r[i] = i*i;for (int j = 2; j <= i; j++)r[i] -= r[i / j];}int t, n;cin >> t;for (int cas = 1; cas <= t; cas++){cin >> n;cout << cas << " " << n << " " << r[n] + 2 << endl;}return 0;}代码很简洁而且非常高效,16ms AC
这个递推式是什么原理呢?
首先解释一下,这个r不是答案,r+2才是答案,也就是说,
我没有计算x=0或者y=0的情况,也就是没有计算(0,1)和(1,0)这2个点。
然后怎么算r呢?
枚举gcd(x,y)
gcd(x,y)=1的情况有r[n]种,gcd(x,y)=2的情况有r[n/2]种
gcd(x,y)=3的情况有r[n/3]种......
所有的加起来,一共是n*n,这就得到了递推式。
- POJ 3090 ZOJ 2777 UVALive 3571 Visible Lattice Points(用递推比用欧拉函数更好)
- zoj 2777 || poj 3090 Visible Lattice Points
- POJ 3090 Visible Lattice Points (ZOJ 2777)
- ZOJ 2777 Visible Lattice Points
- Poj 3090 Visible Lattice Points(欧拉函数)
- POJ 3090 Visible Lattice Points(欧拉函数)
- POJ 3090 Visible Lattice Points(欧拉函数)
- POJ 3090 Visible Lattice Points (欧拉函数)
- POJ 3090 Visible Lattice Points(莫比乌斯反演)
- POJ 3090 Visible Lattice Points
- poj 3090 Visible Lattice Points
- poj 3090 Visible Lattice Points
- POJ 3090 Visible Lattice Points
- POJ 3090 Visible Lattice Points
- POJ 3090 Visible Lattice Points
- POJ - 3090 Visible Lattice Points
- POJ 3090 Visible Lattice Points
- poj Visible Lattice Points(3090)
- Android 插件化原理解析(2):Hook 机制之动态代理
- QT信号和槽以结构体为参数传递
- c++编译报warning: control reaches end of non-void function
- Objective-C 获取控件 详解
- Android 插件化原理解析(3):Hook 机制之 Binder Hook
- POJ 3090 ZOJ 2777 UVALive 3571 Visible Lattice Points(用递推比用欧拉函数更好)
- oracle for update和for update nowait的区别
- iOS导航栏的正确隐藏方式
- Java I/O工作机制
- linux操作系统:系统信息命令
- maven中properties标签定义变量
- Android 插件化原理解析(4):Hook 机制之 AMS & PMS
- HTTP的get,post,HttpClient三种方式向服务器端提交文本数据
- com.umeng.socialize.handler.QZoneSsoHandler$4