HDU 1558 Segment set(线段相交+并查集)
http://acm.hdu.edu.cn/showproblem.php?pid=1558
题意:
依次给你多条线段,然后你需要回答每个Q询问:当前第i条线段所属集合的大小? 每个线段集合中的任意两条线段要么直接相交要么通过其他线段间接相连.
分析:
对于每条新输入的线段,我们都要用它去与之前输入的所有线段判断,看看是否相交.如果相交就合并并查集.
对于每条询问直接输出该线段所属并查集的大小即可.
判断线段相交用刘汝佳的模板,注意端点相交也算相交.
AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=1000+10;
const double eps=1e-10;
int dcmp(double x)
{
if(fabs(x)<eps) return 0;
return x<0?-1:1;
}
struct Point
{
double x,y;
Point(){}
Point(double x,double y):x(x),y(y){}
};
typedef Point Vector;
Vector operator-(Point A,Point B)
{
return Vector(A.x-B.x,A.y-B.y);
}
double Dot(Vector A,Vector B)
{
return A.x*B.x+A.y*B.y;
}
double Cross(Vector A,Vector B)
{
return A.x*B.y-A.y*B.x;
}
bool InSegment(Point P,Point A,Point B)
{
return dcmp(Cross(A-P,B-P))==0 && dcmp(Dot(A-P,B-P))<=0;
}
bool SegmentIntersection(Point a1,Point a2,Point b1,Point b2)
{
double c1=Cross(a2-a1,b1-a1),c2=Cross(a2-a1,b2-a1);
double c3=Cross(b2-b1,a1-b1),c4=Cross(b2-b1,a2-b1);
if(dcmp(c1)*dcmp(c2)<0 && dcmp(c3)*dcmp(c4)<0 ) return true;
if(dcmp(c1)==0 && InSegment(b1,a1,a2)) return true;
if(dcmp(c2)==0 && InSegment(b2,a1,a2)) return true;
if(dcmp(c3)==0 && InSegment(a1,b1,b2)) return true;
if(dcmp(c4)==0 && InSegment(a2,b1,b2)) return true;
return false;
}
/******/
int cnt;//当前线段数目
Point seg[maxn][2];//线段
int fa[maxn];
int sum[maxn];//sum[i]表示第i个并查集的节点数
int findset(int x)
{
return fa[x]==-1?x:fa[x]=findset(fa[x]);
}
void bind(int i,int j)
{
int fi=findset(i);
int fj=findset(j);
if(fi!=fj)
{
fa[fi]=fj;
sum[fj]+=sum[fi];
}
}
int main()
{
int T; scanf("%d",&T);
for(int kase=1;kase<=T;kase++)
{
if(kase>1) printf("\n");
memset(fa,-1,sizeof(fa));
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++) sum[i]=1;//初始化
cnt=0;//cnt记录当前线段数目
while(n--)
{
char type;
scanf(" %c",&type);
if(type=='P')
{
cnt++;
scanf("%lf%lf%lf%lf",&seg[cnt][0].x,&seg[cnt][0].y,&seg[cnt][1].x,&seg[cnt][1].y);
for(int i=1;i<cnt;++i)
if(SegmentIntersection(seg[i][0],seg[i][1],seg[cnt][0],seg[cnt][1]))
bind(i,cnt);
}
else if(type=='Q')
{
int k; scanf("%d",&k);
printf("%d\n",sum[findset(k)]);
}
}
}
return 0;
}