题意:
有一些圆形的镜子,一束光线射进来,试模拟光线的反射过程

测试数据:
/Files/yzhw/reflect.rar解法:
这个问题首先从整体上看应该用迭代法,每次确定v向量和初始位置,然后循环10次即可
下面解决2个问题:
1、求与某个圆的的第一个交点
2、求新的速度矢量
对以第一个问题,我们设参数k,然后列方程:
设x',y'为圆心坐标,r为半径。x0,y0为初始点,(dx,dy)为速度矢量
那么有
(x0+kdx-x')
2+(y0+kdy-y')
2=r
2
如果delta<0,那么说明直线与圆没有交点
否则取k=(-b-sqrt(delta))/2a
如果k<=0,则说明交点在射线的反方向或者交点就在原来的位置,不满足题意
第一个问题算比较好的解决了。
第二个问题我觉得比较简单的方法是利用向量的旋转矩阵

蓝色的向量和红色的向量在知道交点后是很容易算出的。cosθ利用向量夹角公式也不是问题,由于θ肯定是锐角,sinθ也不是问题了。
然后就可以利用旋转矩阵将红色的向量右旋得到目标速度向量(不一定是右旋,如果光线从红色向量右侧射入,那么就要左旋了。判断左右可以用叉积或者干脆直接将两个向量都求出,选择与原来那个不同的向量即可)。
旋转矩阵(左旋):
[cosθ -sinθ]
[sinθ cosθ]
有一点要注意:精度卡到1e-8就够了,求sin的时候sqrt(1-cos*cos+
eps),不然可能会出现-0.000000001这种情况。。。
代码:
1
# include <cstdio>
2
# include <cmath>
3
# include <cstdlib>
4
using namespace std;
5
# define eps 1e-8
6
struct circle
7

{
8
double x,y,r;
9
}cir[30];
10
int n,id[30];
11
double tmp[30][4];
12
double dx,dy,x0,y00;
13
inline double dis(double x1,double y1,double x2,double y2)
14

{
15
return (((x1)-(x2))*((x1)-(x2))+((y1)-(y2))*((y1)-(y2)));
16
}
17
inline bool less(double n1,double n2)
18

{
19
return (fabs((n1)-(n2))>eps&&(n1)<(n2));
20
}
21
inline bool gt(double n1,double n2)
22

{
23
return (fabs((n1)-(n2))>eps&&(n1)>(n2));
24
}
25
void cal(circle &pos,int &count,int _id)
26

{
27
double b=2.0*((x0-pos.x)*dx+(y00-pos.y)*dy),a=dx*dx+dy*dy,c=(x0-pos.x)*(x0-pos.x)+(y00-pos.y)*(y00-pos.y)-pos.r*pos.r;
28
double delta=b*b-4.0*a*c;
29
if(less(delta,0)) return;
30
else
31
{
32
double k=(-b-sqrt(delta))/2.0/a;
33
if(!gt(k,0)) return;
34
id[count]=_id;
35
tmp[count][0]=x0+dx*k;
36
tmp[count][1]=y00+dy*k;
37
double x2=tmp[count][0]-pos.x,y2=tmp[count][1]-pos.y;//连心线向量
38
double x1=x0-tmp[count][0],y1=y00-tmp[count][1];//原向量
39
double cs=(x1*x2+y2*y1)/sqrt(x1*x1+y1*y1)/sqrt(x2*x2+y2*y2);//计算cos
40
double sn=sqrt(1-cs*cs);//计算sin
41
if(less(x1*y2-x2*y1,0))//点积判断左右情况
42
x1=cs*x2+sn*y2,y1=-sn*x2+cs*y2;
43
else if(gt(x1*y2-x2*y1,0))
44
x1=cs*x2-sn*y2,y1=sn*x2+cs*y2;
45
else x1=x2,y1=y2;
46
k=sqrt(x1*x1+y1*y1);
47
x1/=k;
48
y1/=k;
49
tmp[count][2]=x1;
50
tmp[count][3]=y1;
51
count++;
52
}
53
}
54
int main()
55

{
56
//freopen("reflect.in","r",stdin);
57
//freopen("ans.txt","w",stdout);
58
int count=1;
59
while(true)
60
{
61
scanf("%d",&n);
62
if(!n) break;
63
for(int i=0;i<n;i++)
64
scanf("%lf%lf%lf",&cir[i].x,&cir[i].y,&cir[i].r);
65
scanf("%lf%lf%lf%lf",&x0,&y00,&dx,&dy);
66
printf("Scene %d\n",count++);
67
for(int t=1;t<=11;t++)
68
{
69
int c=0;
70
for(int i=0;i<n;i++)
71
cal(cir[i],c,i);
72
if(c==0)
73
{
74
printf("inf\n\n");
75
break;
76
}
77
else if(t!=11)
78
{
79
double len=1e16;
80
int target;
81
for(int i=0;i<c;i++)
82
{
83
if(less(dis(x0,y00,tmp[i][0],tmp[i][1]),len))
84
len=dis(x0,y00,tmp[i][0],tmp[i][1]),target=i;
85
}
86
printf("%d ",id[target]+1);
87
x0=tmp[target][0];
88
y00=tmp[target][1];
89
dx=tmp[target][2];
90
dy=tmp[target][3];
91
// printf("%.4f %.4f %.4f %.4f\n",x0,y00,dx,dy);
92
}
93
else printf("
\n\n");
94
}
95
}
96
return 0;
97
}
98
99
100