思路
这道题思路很简单,也就是直接把所有直线表示成点斜式(如果斜率不存在,另外判断)
但是有一个小技巧不注意的话,就会T
两个分数比较大小的时候,可以先预处理分母,全部变为正数,然后直接分母交叉相乘
a/b与c/d比较大小的时候,先把分母全部化成正数,然后直接判断ad与bc的大小
AC代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
struct node{
bool has_k;
ll pointx;
ll yu, yd;
ll up;
ll down;
}a[maxn];
ll num[maxn];
///斜率从小到大排序
bool cmp(node b, node c){
if(!b.has_k && !c.has_k){
return b.pointx < c.pointx;
}
if(!b.has_k && c.has_k) return false;
if(b.has_k && !c.has_k) return true;
if(b.up * c.down == c.up * b.down){
return b.yu * c.yd < c.yu * b.yd;
}
return b.up * c.down < c.up * b.down;
}
int main(){
int t;
scanf("%d", &t);
while(t--){
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++){
ll x1, y1, x2, y2;
scanf("%lld%lld%lld%lld", &x1, &y1, &x2, &y2);
ll u = y2 - y1, d = x2 - x1;///斜率不为0
if(d){
if(d < 0){
a[i].up = -u;
a[i].down = -d;
}
else{
a[i].up = u;
a[i].down = d;
}
a[i].has_k = true;
if(y1 == y2){
a[i].yu = y1;
a[i].yd = 1;
}
else{
ll u = x2 * y1 - x1 * y2;
ll d = x2 - x1;
if(d < 0){
a[i].yu = -u;
a[i].yd = -d;
}
else{
a[i].yu = u;
a[i].yd = d;
}
}
}
else{
a[i].has_k = false;
a[i].pointx = x1;
}
}
sort(a + 1, a + n + 1, cmp);
int cnt = 0;
bool has_k = a[1].has_k;
ll ans = 0, base = 1;
ll u1, d1;///斜率
ll u2, d2;///如果斜率存在与y轴交点
num[++cnt] = 1;
if(has_k){
u1 = a[1].up;
d1 = a[1].down;
u2 = a[1].yu;
d2 = a[1].yd;
}
else{
u2 = a[1].pointx;
}
ll sum = n;
for(int i = 2; i <= n; i++){
if(!has_k || (has_k && a[i].has_k && (u1 * a[i].down == a[i].up * d1))){
num[cnt]++;
if(!has_k && a[i].pointx == u2){
base++;
if(i == n){
ans += (base - 1) * base / 2;
}
}///交点相同
else if(has_k && a[i].yu * d2 == u2 * a[i].yd){
//printf("!!!");
base++;
if(i == n){
ans += (base - 1) * base / 2;
}
}
else{
//printf("!!!\n");
ans += (base - 1) * base / 2;
base = 1;
if(a[i].has_k){
u2 = a[i].yu;
d2 = a[i].yd;
}
else{
u2 = a[i].pointx;
}
}
}///斜率相同
else{
ans += num[cnt] * (sum - num[cnt]);
sum -= num[cnt];
ans += (base - 1) * base / 2;
base = 1;
num[++cnt] = 1;
if(a[i].has_k){
u1 = a[i].up;
d1 = a[i].down;
u2 = a[i].yu;
d2 = a[i].yd;
}
else{
has_k = false;
u2 = a[i].pointx;
}
}
}
printf("%lld\n", ans);
return 0;
}