结果:40257
我自己电脑eclipse跑代码时间是:大约2min
相关知识:
1,比较器无法比较double:借鉴:https://blog.csdn.net/appleml/article/details/41315429
2,1e-8是多少:借鉴:https://bbs.csdn.net/topics/270060700
3,为什么用1e-8,借鉴:https://www.cnblogs.com/lxzbky/p/10506962.html
4,下面使用Double比较判断,出现Double画横线,已被弃用。
使用BIgDecimal判断两个double数大小即可。借鉴:https://blog.csdn.net/qpzkobe/article/details/80820254
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
//两种情况考虑
//1,横坐标相同时单独处理。最后+20即可。
//2,横坐标不同时,计算直线。采用截距式。
public class 第三题 {
static class line{
double k;
double b;
public line(double k, double b) {
// TODO Auto-generated constructor stub
this.k = k;
this.b = b;
}
}
public static void main(String[] args) {
//截距式
List<line> list = new LinkedList<line>();
for(int x1 = 0; x1 <= 19; x1 ++) {
for(int y1 = 0; y1 <= 20; y1 ++) {
for(int x2 = 0; x2 <= 19; x2 ++) {
for(int y2 = 0; y2 <= 20; y2 ++) {
// 两个点横坐标不相同时,计算直线。
if(x1 != x2) {
double k = (double)(y2 - y1) / (x2 - x1);
double b = y1 - k * x1;
list.add(new line(k, b));
}
}
}
}
}
//所有元素元素整体筛选去重,必须先排序。
Collections.sort(list,new Comparator<line>() {
@Override
public int compare(第三题.line o1, 第三题.line o2) {
// TODO Auto-generated method stub
//这里的比较规则是按k 和 b升序排列
//double比较是否相同时,要两数做差,取绝对值, 小于1e-8,为相等。大于,则不等。
if(Math.abs(o1.k - o2.k) > 1e-8) return new Double(o1.k).compareTo(new Double(o2.k));
return new Double(o1.b).compareTo(new Double(o2.b));
//使用BigDecimal也可以。
//if(Math.abs(o1.k - o2.k) > 1e-8) return new BigDecimal(o1.k).compareTo(new BigDecimal(o2.k));
// return new BigDecimal(o1.b).compareTo(new BigDecimal(o2.b));
}
});
// count为什么不是从0开始呢??
// 因为从0开始,最后结果会少1,因为是两两比较,不同时加1,但实际是这两个数不同
int count = 1;
for(int i = 1; i < list.size(); i++) {
if(Math.abs(list.get(i).k - list.get(i - 1).k) > 1e-8 || Math.abs(list.get(i).b - list.get(i - 1).b) > 1e-8 ) {
count ++;
}
}
System.out.println(count + 20);
}
}