geometry - C++ : Modified Line Segment Intersection -
given n lines (either horizontal or vertical), need find total intersection of these line segments intersections per line. code follows :
using namespace std; #define x second #define y first #define max 10000 typedef pair<int,int >point; struct event { point p1,p2; int type; event() {}; event(point p1,point p2, int type) : p1(p1), p2(p2),type(type) {}; //initialization of event }; int n,e; event events[max]; bool compare(event a, event b) { return a.p1.x<b.p1.x; } set<point >s; int hv_intersection() { ll count=0; (ll i=0;i<e;++i) { event c = events[i]; if (c.type==0) s.insert(c.p1);//insert starting point of line segment set else if (c.type==1) s.erase(c.p2);//remove starting point of line segment set, equivalent removing line segment else { (typeof(s.begin()) it=s.lower_bound(make_pair(c.p1.y,-1));it!=s.end() && it->y<=c.p2.y; it++) // range search { printf("%d, %d\n", events[i].p1.x, it->y);//intersections count++; } } } return count; } int main () { scanf("%d", &n); ll p1x,p1y,p2x,p2y; (int i=0;i<n;++i) { scanf("%d %d %d %d", &p1x, &p1y,&p2x, &p2y); if(p1x==p2x) //if vertical line, 1 event type=2 { events[e++]=event(make_pair(p1y,p1x),make_pair(p2y,p2x),2); } else //if horizontal line, 2 events 1 starting point , 1 ending point { //store both starting points , ending points events[e++]=event(make_pair(p1y,p1x),make_pair(p2y,p2x),0); //store both ending , starting points, note order in second, because sort on p1, ending points first, remove line when hit ending point , need starting point removal of line events[e++]=event(make_pair(p2y,p2x),make_pair(p1y,p1x),1); } } sort(events, events+e,compare);//on x coordinate int count= hv_intersection(); cout<<"count="<<count; return 0; }
for following input :
5 // number of lines 0 0 0 3 // x1,y1,x2,y2 2 0 2 5 3 0 3 5 0 0 3 0 0 3 3 3
output :
2, 0 2, 3 3, 0 3, 3 count=4
now can't figure out how following things :
1.the intersection should not there when both line segments end point meet. 1 end point can lie on other line segment though i.e (3,0) incorrect. valid intersection points according conditions :
(2,0) , (2,3), (3,3)
2. want calculate number of intersections per line i.e. desired output should be:
0 2 1 1 2 count=3
i.e.
0 0 0 3 has 0 intersection 2 0 2 5 has 2 intersections 3 0 3 5 has 1 intersection 0 0 3 0 has 1 intersection 0 3 3 3 has 2 intersections
can me out in correcting these 2 mistakes in code ?
Comments
Post a Comment