Segment set
A segment and all segments which are connected with it compose a segment set. The size of a segment set is the number of segments in it. The problem is to find the size of some segment set.
Input
In the first line there is an integer t - the number of test case. For each test case in first line there is an integer n (n<=1000) - the number of commands.
There are two different commands described in different format shown below:
P x1 y1 x2 y2 - paint a segment whose coordinates of the two endpoints are (x1,y1),(x2,y2).
Q k - query the size of the segment set which contains the k-th segment.
k is between 1 and the number of segments in the moment. There is no segment in the plane at first, so the first command is always a P-command.
Output
For each Q-command, output the answer. There is a blank line between test cases.
Sample Input
1
10
P 1.00 1.00 4.00 2.00
P 1.00 -2.00 8.00 4.00
Q 1
P 2.00 3.00 3.00 1.00
Q 1
Q 3
P 1.00 4.00 8.00 2.00
Q 2
P 3.00 3.00 6.00 -2.00
Q 5
Sample Output
1
2
2
2
5
题意:有n个命令,是P的时候就是加入一条线段(x1,y1),(x2,y2)在平面上,如果是Q时,就输出第k条线段所在同一集合的线段的数目(相交的两条线段在同一集合)
分析:运用并查集,每次加入一条线段就跟之前的线段判断是否相交,然后并入同一集合中,判断相交运用计算几何中线段相交的知识。
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
int n;
int fa[1005];//父节点
int num[1005];//数目
int find(int x){//查
return x==fa[x]?x:fa[x]=find(fa[x]);
}
void merge(int u,int v){//并
int fu=find(u);
int fv=find(v);
if (fu==fv)return ;
fa[fu]=fv;
num[fv]+=num[fu];
}
struct point {//点
double x;
double y;
};
struct edge{//线段
point a;
point b;
};
edge e[1005];
double chaji(point a,point b,point c){//判断点c在线段ab的左边,右边还是在直线ab上
double x1,x2,y1,y2;
x1=b.x-a.x;y1=b.y-a.y;
x2=c.x-a.x;y2=c.y-a.y;
return x1*y2-x2*y1;//大于0在左边,小于0在右边,等于0在同一直线上
}
int onSegment(point a,point b,point c){//判断点c是否在线段ab之间
return c.x>=min(a.x,b.x)&&c.x<=max(a.x,b.x)&&c.y>=min(a.y,b.y)&&c.y<=max(b.y,a.y);
}
int cross(point a,point b,point c,point d){//判断ab与cd是否相交
double d1,d2,d3,d4;
d1=chaji(a,b,c);//判断c在线段ab的那一边
d2=chaji(a,b,d);//同上
d3=chaji(c,d,a);
d4=chaji(c,d,b);
if (d1*d2<0 && d3*d4<0) return 1;//相交
if (d1==0&&onSegment(a,b,c)) return 1;//c在线段ab上面
if (d2==0&&onSegment(a,b,d)) return 1;//类似上面
if (d3==0&&onSegment(c,d,a)) return 1;
if (d4==0&&onSegment(c,d,b)) return 1;
return 0;
}
int main ()
{
int t;
cin>>t;
char c;
int cnt=0;
while (t--){
cnt=0;
for (int i=1;i<=1000;i++){
fa[i]=i;
num[i]=1;
}
cin>>n;
while (n--){
cin>>c;
if (c=='P'){
cnt++;
cin>>e[cnt].a.x>>e[cnt].a.y>>e[cnt].b.x>>e[cnt].b.y;//输入
for (int i=1;i<cnt;i++){//遍历之前的边
if (cross(e[cnt].a,e[cnt].b,e[i].a,e[i].b)){
merge(cnt,i);//如果相交就并起来
}
}
}
else {
int order;//输入
cin>>order;
cout<<num[find(order)]<<endl;//输出结果
}
}
if (t)cout<<endl;
}
return 0;
}