题意:按照顺序丢下n根棍子,求所有未被其他棍子压在下面的棍子(top sticks)序号
1 <= n <= 100000,top sticks数量不超过1000
题解:开一个vector(叫top),每次扔下一根棍子,把它push_back进去(这根棍子当前一定未被压在下面),然后遍历top,把所有和这个棍子相交的序号都删除掉。
理论上时间复杂度可以达到O(n2),因为虽然答案元素不超过1000,但中间过程vector可以几乎到达n,除非说“任意时刻top sticks数量不超过1000”,但是还是A了,不知道有没有更好的解法。
#include<cmath> #include<cstdio> #include<cstring> #include<algorithm> #include<vector> using namespace std; #define rep(i,a,b) for (int i=a;i<=b;++i) const double eps=1e-10; struct point{ double x,y; point(){} point (double a,double b): x(a),y(b) {} friend point operator + (const point &a,const point &b){ return point(a.x+b.x,a.y+b.y); } friend point operator - (const point &a,const point &b){ return point(a.x-b.x,a.y-b.y); } friend point operator * (const double &r,const point &a){ return point(r*a.x,r*a.y); } friend bool operator == (const point &a,const point &b){ return (abs(a.x-b.x)<eps && abs(a.y-b.y)<eps); } double norm(){ return sqrt(x*x+y*y); } }; inline double det(point a,point b) {return a.x*b.y-a.y*b.x;} inline bool seg_cross_seg(point a,point b,point c,point d) { if (min(c.x,d.x)>max(a.x,b.x) || min(a.x,b.x)>max(c.x,d.x) || min(c.y,d.y)>max(a.y,b.y) || min(a.y,b.y)>max(c.y,d.y)) return false; return det(a-c,d-c)*det(b-c,d-c)<eps && det(c-a,b-a)*det(d-a,b-a)<eps; } int n; point s[200000],t[200000]; vector<int> top; int main() { bool flag; while (~scanf("%d",&n)) { if (n==0) break; rep(i,1,n) scanf("%lf%lf%lf%lf",&s[i].x,&s[i].y,&t[i].x,&t[i].y); top.clear(); rep(i,1,n) { for (vector<int>::iterator it=top.begin();it!=top.end();) { if (seg_cross_seg(s[*it],t[*it],s[i],t[i])) { it=top.erase(it); } else ++it; } top.push_back(i); } printf("Top sticks:"); for(int i=0;i<top.size()-1;++i) printf(" %d,",top[i]); printf(" %d. ",top[top.size()-1]); } return 0; }