didhv 题解分享 · 2024/4/4
直线(结果填空) - 题解
``` import java.util.HashSet; // 导入HashSet集合,用于存储不重复的直线对象。 import java.util.Objects; // 导入Objects类,提供了一些静态方法来操作对象,如计算哈希码和比较对象。 public class 直线 { /** * 主方法,程序执行的入口。 */ public static void main(String[] args) { HashSet<line> lines = new HashSet<>(); // 创建一个HashSet来存储不重复的直线对象。 // 通过嵌套循环遍历所有可能的点对,以计算不同的直线。 for (int x1 = 1; x1 <= 19; x1++) { // 第一层循环:x1的值从1到19。 for (int y1 = 0; y1 <= 20; y1++) { // 第二层循环:y1的值从0到20。 for (int x2 = 0; x2 <= x1 - 1; x2++) { // 第三层循环:x2的值从0到x1-1,确保x2小于x1,避免重复。 for (int y2 = 0; y2 <= 20; y2++) { // 第四层循环:y2的值从0到20。 line l1 = new line(x1, y1, x2, y2); // 对于每个点对,创建一个新的直线对象。 l1.k_d(); // 计算并设置直线的斜率k和截距d。 lines.add(l1); // 将新的直线对象添加到HashSet中,自动去除重复的直线。 } } } } System.out.println(lines.size() + 20); // 输出去重后的直线数量加上20的结果。 } } class line { public double k; // 直线的斜率。 public double d; // 直线的截距。 public int x1, y1, x2, y2; // 直线通过的两个点的坐标。 // 构造函数,初始化直线对象。 public line(int x1, int y1, int x2, int y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } // 计算斜率和截距的方法。 public void k_d() { if (this.x1 != this.x2) { // 如果两点的x坐标不相同,计算斜率和截距。 this.k = (double) (this.y2 - this.y1) / (this.x2 - this.x1); this.d = (double) (this.x2 * this.y1 - this.x1 * this.y2) / (this.x2 - this.x1); } else if (this.y1 == this.y2) { // 如果两点的x坐标相同且y坐标也相同,视为水平直线。 this.k = 0; this.d = this.y1; } else { // 如果两点的x坐标相同但y坐标不同,视为垂直直线。 this.k = 999999999; // 用一个非常大的数表示斜率为无限大。 this.d = x1; // 垂直直线的“截距”可以用任意一点的x坐标表示。 } } @Override public boolean equals(Object o) { if (this == o) return true; // 自反性检查。 if (o == null || getClass() != o.getClass()) return false; // 类型检查。 line line = (line) o; // 类型转换,将Object转换为line对象。 return Double.compare(k, line.k) == 0 && Double.compare(d, line.d) == 0; // 比较两条直线的斜率和截距是否相等。 } @Override public int hashCode() { return Objects.hash(k, d); // 根据斜率和截距计算hashCode值,确保相同的直线有相同的hashCode。 } @Override public String toString() { return "line{" + "k=" + k + ", d=" + d + '}'; // 返回直线对象的字符串表示,包含斜率和截距信息。 } } ```
查看全文
0 0 0 6
fpy游戏人生 题解分享 · 2024/4/11
直线(结果填空) - 题解
本题的关键就在于是否想到了set排序,记住set排序还有map,multiset,multimap的区别,且都属于红黑树的一类,以及pair的应用(本人当时做题也忘了,所以看了一下题解,就悟了),还有记得将int类型的x1,x2,y1,y2转换为浮点型(避免高精度带来的误差,如果有一个没有1.0答案是15365)证明你错了 include using namespace std; typedef pair P; int n=20,m=21; set sl; void check(int x1,int y1,int x2,int y2) { ``` if(x1==x2||y1==y2) return ; double k,b; k=(y2-y1)\*1.0/(x2-x1); b=(y1\*x2-y2\*x1)\*1.0/(x2-x1); sl.insert({k,b}); ``` } int main(){ ``` for(int x1=0;x1<n;x1++) for(int y1=0;y1<m;y1++) for(int x2=0;x2<n;x2++) for(int y2=0;y2<m;y2++) check(x1,y1,x2,y2); ``` cout<<sl.size()+n+m; }
查看全文
0 0 0 0