题意 : 有n条线段可能相交,问你最后顶上的线段一共有多少条。
题解 : 关键在于注意到这个题目 top sticks 最多不会超过 1000 这是这个题目的关键,我们可以从前往后依次将可能在顶上的线段放进一个数组里,然后每次对于一条新的线段,枚举判断是否与前面的线段相交相交的话把前面的线段从答案中删除就可以了。
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 1e6 + 10;
int res[maxn] = {0};
struct seg {
double x1,y1,x2,y2;
}segment[maxn];
double corss (double x1,double y1,double x2,double y2) {
return x1 * y2 - x2 * y1;
}
bool judge (seg a,seg b) {
double ax1 = a.x1,ax2 = a.x2,ay1 = a.y1,ay2 = a.y2;
double bx1 = b.x1,bx2 = b.x2,by1 = b.y1,by2 = b.y2;
if (!(max (ax1,ax2) >= min (bx1,bx2) && max (bx1,bx2) >= min (ax1,ax2) && max (ay1,ay2) >= min(by1,by2) && max (by1,by2) >= min(ay1,ay2)) ) return false;
if (corss(ax2 - ax1, ay2 - ay1, bx1 - ax1, by1 - ay1) * corss(ax2 - ax1, ay2 - ay1, bx2 - ax1, by2 - ay1) < 0) {
if (corss(bx2 - bx1, by2 - by1, ax1 - bx1, ay1 - by1) * corss(bx2 - bx1, by2 - by1, ax2 - bx1, ay2 - by1) < 0)
return true;
}
return false;
}
int main () {
int n;
while (scanf ("%d",&n) && n) {
for (int i = 1;i <= n; ++ i) {
scanf ("%lf%lf%lf%lf",&segment[i].x1,&segment[i].y1,&segment[i].x2,&segment[i].y2);
}
int temp = 0;
for (int i = 1;i <= n; ++ i) {
int cnt = temp;
temp = 0;
for (int j = 0;j < cnt; ++ j) {
if (!judge(segment[i], segment[res[j]])) {
res[temp ++] = res[j];
}
}
res[temp ++] = i;
}
int cnt = temp;
printf ("Top sticks: ");
for (int i = 0;i < cnt - 1; ++ i) {
printf ("%d, ",res[i]);
}
printf("%d.\n",res[cnt - 1]);
}
return 0;
}