本题主要要去除重复的直线和直线交点,然后切成的平面数量为1+不同直线数量+不同交点数量
但是注意java要重写equals()与hashCode()方法,因为java是用地址来判断所以要重写
idea重写快捷键 Alt+Insert
eclipse重写快捷键 Alt+shift+s 然后加h
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] a = new int[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = sc.nextInt();
a[i][1] = sc.nextInt();
for(int j=0;j<i;j++){
if(a[i][0]==a[j][0]&&a[i][1]==a[j][1]){
i--;
n--;
break;
}
}
}
int count = 2;
for (int i = 1; i < n; i++) {
int c = 1;
Set<Point> set = new HashSet<>();
for (int j = 0; j < i; j++) {
if (a[i][0] == a[j][0]){
continue;
}
double x = (a[i][1] - a[j][1])*1.0 / (a[j][0] - a[i][0]) + 0.0;
double y = a[i][0] * x + a[i][1] + 0.0;
Point p = new Point(x, y);
if (!set.contains(p)) {
set.add(p);
c++;
}
}
count+=c;
}
System.out.println(count);
sc.close();
}
}
/**
* @author forward
*
*/
class Point {
private double x;
private double y;
public Point(Double x, Double y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point other = (Point) obj;
return Double.doubleToLongBits(x) == Double.doubleToLongBits(other.x)
&& Double.doubleToLongBits(y) == Double.doubleToLongBits(other.y);
}
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Point point = (Point) o;
// return Double.compare(point.x, x) == 0 && Double.compare(point.y, y) == 0;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(x, y);
// }
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Point point = (Point) o;
// return x == point.x &&
// y == point.y;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(x, y);
// }
}
C++代码
#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>
#include<cmath>
#include<queue>
#include<set>
using namespace std;
const int N=1e4+10;
typedef pair<long double,long double>PII;
set<PII>s;//存放直线
set<PII>points;//存放交点
long double k[N],b[N];
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
long double kk,bb;
scanf("%llf%llf",&kk,&bb);
s.insert({kk,bb});
}
int tt=0;
set<PII>::iterator it;//set迭代器
for(it=s.begin();it!=s.end();it++)
{
k[++tt]=(*it).first;
b[tt]=(*it).second;
}
long long ans=2;//从第二条直线开始遍历,第一条直线将平面划分为2部分
for(int i=2;i<=tt;i++)
{
points.clear();
for(int j=1;j<i;j++)
{
if(k[i]==k[j])
continue;//两直线平行则不可能有交点
long double x=(b[j]-b[i])/(k[i]-k[j]);
long double y=(k[i]*b[j]-k[j]*b[i])/(k[i]-k[j]);
points.insert({x,y});
}
ans+=points.size()+1;//当前直线与其他直线有m个交点那么就会多产生m+1块区域
}
printf("%lld",ans);
return 0;
}