0
点赞
收藏
分享

微信扫一扫

hdu 1558 Segment set(线段相交+并查集)

其生 2022-08-09 阅读 77


题目:​​http://acm.hdu.edu.cn/showproblem.php?pid=1558​​

Problem Description

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.



hdu 1558 Segment set(线段相交+并查集)_hdu


 



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

 



Author


LL

题目叙述很清楚,相交的线段属于同一集合,问一共有多少个集合。判断线段相交是一个点,集合数目问题又是一个点。把这两个点搞定就能解决问题。


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

int pre[1010],sum[1010];
struct point{
double x,y;
};
struct node{
point a,b;
} edge[1010];
int myedges;

int Find(int x){
if(x!=pre[x]){
pre[x]=Find(pre[x]);
}
return pre[x];
}

void Merge(int a,int b){
int x=Find(a),y=Find(b);
if(x!=y){
pre[y]=x;
sum[x]+=sum[y];
}
}

double crossmulti(point a,point b,point c){
return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
}
bool OnSegment(point a,point b,point c){ //a,b,c共线时使用
if(c.x>=min(a.x,b.x)&&c.x<=max(a.x,b.x)&&c.y>=min(a.y,b.y)&&c.y<=max(a.y,b.y))return 1;
return 0;
}

bool Cross(point a,point b,point c,point d){ //判断ab 与cd是否相交
double re1,re2,re3,re4;
re1=crossmulti(c,d,a);
re2=crossmulti(c,d,b);
re3=crossmulti(a,b,c);
re4=crossmulti(a,b,d);
if(re1*re2<0&&re3*re4<0) return 1;
else if(re1==0&&OnSegment(c,d,a)) return 1; //四种在同一条线上的结果
else if(re2==0&&OnSegment(c,d,b)) return 1;
else if(re3==0&&OnSegment(a,b,c)) return 1;
else if(re4==0&&OnSegment(a,b,d)) return 1;
return 0;
}

int main()
{
//freopen("cin.txt",&qumt;r",stdin);
int i,j,k,t,n;
cin>>t;
while(t--)
{
int i,j,k,n;
char s[10];
scanf("%d",&n);
myedges=0;
for(i=1;i<=n;i++){
pre[i]=i;
sum[i]=1;
}
for(i=1;i<=n;i++)
{
scanf("%s",s);
if(s[0]=='P'){
myedges++;
scanf("%lf%lf%lf%lf",&edge[myedges].a.x,&edge[myedges].a.y,&edge[myedges].b.x,&edge[myedges].b.y);
for(j=1;j<myedges;j++)
if(Find(myedges)!=Find(j)&&Cross(edge[myedges].a,edge[myedges].b,edge[j].a,edge[j].b))
Merge(myedges,j);
}
else if(s[0]=='Q'){
scanf("%d",&k);
printf("%d\n",sum[Find(k)]);
}
}
if(t>0) printf("\n");
}
return 0;
}




举报

相关推荐

0 条评论