0

给定N行(水平或垂直),我需要找到这些线段的总交点以及每条线的交点。我的代码如下:

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;
    for (ll i=0;i<e;++i)
        {
                event c = events[i];
                if (c.type==0) s.insert(c.p1);//insert starting point of line segment into set
                else if (c.type==1) s.erase(c.p2);//remove starting point of line segment from set, equivalent to removing line segment
                else
                {
                        for (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;
        for (int i=0;i<n;++i) 
        {
                scanf("%d %d %d %d", &p1x, &p1y,&p2x, &p2y);
        if(p1x==p2x)                //if vertical line, one event with type=2
        {
            events[e++]=event(make_pair(p1y,p1x),make_pair(p2y,p2x),2);
        }
        else                    //if horizontal line, two events one for starting point and one for ending point
        {
            //store both starting points and ending points
            events[e++]=event(make_pair(p1y,p1x),make_pair(p2y,p2x),0);
            //store both ending and starting points, note the order in the second, this is because we sort on p1, so ending points first, then we remove a line when we hit its ending point , so we need its starting point for 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;
}

对于以下输入:

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

输出 :

2, 0
2, 3
3, 0
3, 3
count=4

现在我不知道如何做以下事情:

1.两条线段端点相交时不应有交点。一个端点可以位于另一条线段上,尽管(3,0) 是不正确的。根据我的条件,有效的交点是:

(2,0) , (2,3), (3,3)

2.我想计算每条线的交叉点数,即期望的输出应该是:

0 2 1 1 2

count=3 

IE

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

有人可以帮我纠正这两个代码错误吗?

4

0 回答 0