计算几何算法概览
|
一、引言
计算机的出现使得很多原本十分繁琐的工作得以大幅度简化,但是也有一些在人们直观看来很容易的问题却需要拿出一套并不简单的通用解决方案,比如几何问题。作为计算机科学的一个分支,计算几何主要研究解决几何问题的算法。在现代工程和数学领域,计算几何在图形学、机器人技术、超大规模集成电路设计和统计等诸多领域有着十分重要的应用。在本文中,我们将对计算几何常用的基本算法做一个全面的介绍,希望对您了解并应用计算几何的知识解决问题起到帮助。
二、目录
本文整理的计算几何基本概念和常用算法包括如下内容:
矢量的概念
矢量加减法
矢量叉积
折线段的拐向判断
判断点是否在线段上
判断两线段是否相交
判断线段和直线是否相交
判断矩形是否包含点
判断线段、折线、多边形是否在矩形中
判断矩形是否在矩形中
判断圆是否在矩形中
判断点是否在多边形中
判断线段是否在多边形内
判断折线是否在多边形内
判断多边形是否在多边形内
判断矩形是否在多边形内
判断圆是否在多边形内
判断点是否在圆内
判断线段、折线、矩形、多边形是否在圆内
判断圆是否在圆内
计算点到线段的最近点
计算点到折线、矩形、多边形的最近点
计算点到圆的最近距离及交点坐标
计算两条共线的线段的交点
计算线段或直线与线段的交点
求线段或直线与折线、矩形、多边形的交点
求线段或直线与圆的交点
凸包的概念
凸包的求法
三、算法介绍
如果一条线段的端点是有次序之分的,我们把这种线段成为有向线段(directed segment)。如果有向线段p1p2的起点p1在坐标原点,我们可以把它称为矢量(vector)p2。
设二维矢量P = ( x1, y1 ),Q = ( x2 , y2 ),则矢量加法定义为: P + Q = ( x1 + x2 , y1 + y2 ),同样的,矢量减法定义为: P - Q = ( x1 - x2 , y1 - y2 )。显然有性质 P + Q = Q + P,P - Q = - ( Q - P )。
矢量叉积:
计算矢量叉积是与直线和线段相关算法的核心部分。设矢量P = ( x1, y1 ),Q = ( x2, y2 ),则矢量叉积定义为由(0,0)、p1、p2和p1+p2所组成的平行四边形的带符号的面积,即:P × Q = x1*y2 - x2*y1,其结果是一个标量。显然有性质 P × Q = - ( Q × P ) 和 P × ( - Q ) = - ( P × Q )。一般在不加说明的情况下,本文下述算法中所有的点都看作矢量,两点的加减法就是矢量相加减,而点的乘法则看作矢量叉积。
叉积的一个非常重要性质是可以通过它的符号判断两矢量相互之间的顺逆时针关系:
若 P × Q > 0 , 则P在Q的顺时针方向。
若 P × Q < 0 , 则P在Q的逆时针方向。 若 P × Q = 0 , 则P与Q共线,但可能同向也可能反向。
折线段的拐向判断方法可以直接由矢量叉积的性质推出。对于有公共端点的线段p0p1和p1p2,通过计算(p2 - p0) × (p1 - p0)的符号便可以确定折线段的拐向:
若(p2 - p0) × (p1 - p0) > 0,则p0p1在p1点拐向右侧后得到p1p2。
若(p2 - p0) × (p1 - p0) < 0,则p0p1在p1点拐向左侧后得到p1p2。
若(p2 - p0) × (p1 - p0) = 0,则p0、p1、p2三点共线。
具体情况可参照下图:
![]()
设点为Q,线段为P1P2 ,判断点Q在该线段上的依据是:( Q - P1 ) × ( P2 - P1 ) = 0 且 Q 在以 P1,P2为对角顶点的矩形内。前者保证Q点在直线P1P2上,后者是保证Q点不在线段P1P2的延长线或反向延长线上,对于这一步骤的判断可以用以下过程实现:
ON-SEGMENT(pi,pj,pk)
if min(xi,xj) <= xk <= max(xi,xj) and min(yi,yj) <= yk <= max(yi,yj)
then return true;
else return false;
特别要注意的是,由于需要考虑水平线段和垂直线段两种特殊情况,min(xi,xj)<=xk<=max(xi,xj)和min(yi,yj)<=yk<=max(yi,yj)两个条件必须同时满足才能返回真值。
我们分两步确定两条线段是否相交:
(1)快速排斥试验
设以线段 P1P2 为对角线的矩形为R, 设以线段 Q1Q2 为对角线的矩形为T,如果R和T不相交,显然两线段不会相交。
(2)跨立试验
如果两线段相交,则两线段必然相互跨立对方。若P1P2跨立Q1Q2 ,则矢量 ( P1 - Q1 ) 和( P2 - Q1 )位于矢量( Q2 - Q1 ) 的两侧,即( P1 - Q1 ) × ( Q2 - Q1 ) * ( P2 - Q1 ) × ( Q2 - Q1 ) < 0。上式可改写成( P1 - Q1 ) × ( Q2 - Q1 ) * ( Q2 - Q1 ) × ( P2 - Q1 ) > 0。当 ( P1 - Q1 ) × ( Q2 - Q1 ) = 0 时,说明 ( P1 - Q1 ) 和 ( Q2 - Q1 )共线,但是因为已经通过快速排斥试验,所以 P1 一定在线段 Q1Q2上;同理,( Q2 - Q1 ) ×(P2 - Q1 ) = 0 说明 P2 一定在线段 Q1Q2上。所以判断P1P2跨立Q1Q2的依据是:( P1 - Q1 ) × ( Q2 - Q1 ) * ( Q2 - Q1 ) × ( P2 - Q1 ) >= 0。同理判断Q1Q2跨立P1P2的依据是:( Q1 - P1 ) × ( P2 - P1 ) * ( P2 - P1 ) × ( Q2 - P1 ) >= 0。具体情况如下图所示: ![]()
在相同的原理下,对此算法的具体的实现细节可能会与此有所不同,除了这种过程外,大家也可以参考《算法导论》上的实现。
有了上面的基础,这个算法就很容易了。如果线段P1P2和直线Q1Q2相交,则P1P2跨立Q1Q2,即:( P1 - Q1 ) × ( Q2 - Q1 ) * ( Q2 - Q1 ) × ( P2 - Q1 ) >= 0。
只要判断该点的横坐标和纵坐标是否夹在矩形的左右边和上下边之间。
因为矩形是个凸集,所以只要判断所有端点是否都在矩形中就可以了。
只要比较左右边界和上下边界就可以了。
很容易证明,圆在矩形中的充要条件是:圆心在矩形中且圆的半径小于等于圆心到矩形四边的距离的最小值。
判断点P是否在多边形中是计算几何中一个非常基本但是十分重要的算法。以点P为端点,向左方作射线L,由于多边形是有界的,所以射线L的左端一定在多边形外,考虑沿着L从无穷远处开始自左向右移动,遇到和多边形的第一个交点的时候,进入到了多边形的内部,遇到第二个交点的时候,离开了多边形,……所以很容易看出当L和多边形的交点数目C是奇数的时候,P在多边形内,是偶数的话P在多边形外。
但是有些特殊情况要加以考虑。如图下图(a)(b)(c)(d)所示。在图(a)中,L和多边形的顶点相交,这时候交点只能计算一个;在图(b)中,L和多边形顶点的交点不应被计算;在图(c)和(d) 中,L和多边形的一条边重合,这条边应该被忽略不计。如果L和多边形的一条边重合,这条边应该被忽略不计。
![]()
为了统一起见,我们在计算射线L和多边形的交点的时候,1。对于多边形的水平边不作考虑;2。对于多边形的顶点和L相交的情况,如果该顶点是其所属的边上纵坐标较大的顶点,则计数,否则忽略;3。对于P在多边形边上的情形,直接可判断P属于多边行。由此得出算法的伪代码如下:
count ← 0; 以P为端点,作从右向左的射线L; for 多边形的每条边s do if P在边s上 then return true; if s不是水平的 then if s的一个端点在L上 if 该端点是s两端点中纵坐标较大的端点 then count ← count+1 else if s和L相交 then count ← count+1; if count mod 2 = 1 then return true; else return false; 其中做射线L的方法是:设P'的纵坐标和P相同,横坐标为正无穷大(很大的一个正数),则P和P'就确定了射线L。
判断点是否在多边形中的这个算法的时间复杂度为O(n)。
另外还有一种算法是用带符号的三角形面积之和与多边形面积进行比较,这种算法由于使用浮点数运算所以会带来一定误差,不推荐大家使用。
线段在多边形内的一个必要条件是线段的两个端点都在多边形内,但由于多边形可能为凹,所以这不能成为判断的充分条件。如果线段和多边形的某条边内交(两线段内交是指两线段相交且交点不在两线段的端点),因为多边形的边的左右两侧分属多边形内外不同部分,所以线段一定会有一部分在多边形外(见图a)。于是我们得到线段在多边形内的第二个必要条件:线段和多边形的所有边都不内交。
线段和多边形交于线段的两端点并不会影响线段是否在多边形内;但是如果多边形的某个顶点和线段相交,还必须判断两相邻交点之间的线段是否包含于多边形内部(反例见图b)。
![]()
因此我们可以先求出所有和线段相交的多边形的顶点,然后按照X-Y坐标排序(X坐标小的排在前面,对于X坐标相同的点,Y坐标小的排在前面,这种排序准则也是为了保证水平和垂直情况的判断正确),这样相邻的两个点就是在线段上相邻的两交点,如果任意相邻两点的中点也在多边形内,则该线段一定在多边形内。
证明如下:
命题1:
如果线段和多边形的两相邻交点P1 ,P2的中点P' 也在多边形内,则P1, P2之间的所有点都在多边形内。
证明:
假设P1,P2之间含有不在多边形内的点,不妨设该点为Q,在P1, P'之间,因为多边形是闭合曲线,所以其内外部之间有界,而P1属于多边行内部,Q属于多边性外部,P'属于多边性内部,P1-Q-P'完全连续,所以P1Q和QP'一定跨越多边形的边界,因此在P1,P'之间至少还有两个该线段和多边形的交点,这和P1P2是相邻两交点矛盾,故命题成立。证毕。
由命题1直接可得出推论:
推论2: 设多边形和线段PQ的交点依次为P1,P2,……Pn,其中Pi和Pi+1是相邻两交点,线段PQ在多边形内的充要条件是:P,Q在多边形内且对于i =1, 2,……, n-1,Pi ,Pi+1的中点也在多边形内。 在实际编程中,没有必要计算所有的交点,首先应判断线段和多边形的边是否内交,倘若线段和多边形的某条边内交则线段一定在多边形外;如果线段和多边形的每一条边都不内交,则线段和多边形的交点一定是线段的端点或者多边形的顶点,只要判断点是否在线段上就可以了。 至此我们得出算法如下: if 线端PQ的端点不都在多边形内 then return false; 点集pointSet初始化为空; for 多边形的每条边s do if 线段的某个端点在s上 then 将该端点加入pointSet; else if s的某个端点在线段PQ上 then 将该端点加入pointSet; else if s和线段PQ相交 // 这时候已经可以肯定是内交了 then return false; 将pointSet中的点按照X-Y坐标排序; for pointSet中每两个相邻点 pointSet[i] , pointSet[ i+1] do if pointSet[i] , pointSet[ i+1] 的中点不在多边形中 then return false; return true; 这个过程中的排序因为交点数目肯定远小于多边形的顶点数目n,所以最多是常数级的复杂度,几乎可以忽略不计。因此算法的时间复杂度也是O(n)。
只要判断折线的每条线段是否都在多边形内即可。设折线有m条线段,多边形有n个顶点,则该算法的时间复杂度为O(m*n)。
只要判断多边形的每条边是否都在多边形内即可。判断一个有m个顶点的多边形是否在一个有n个顶点的多边形内复杂度为O(m*n)。
将矩形转化为多边形,然后再判断是否在多边形内。
只要计算圆心到多边形的每条边的最短距离,如果该距离大于等于圆半径则该圆在多边形内。计算圆心到多边形每条边最短距离的算法在后文阐述。
计算圆心到该点的距离,如果小于等于半径则该点在圆内。
因为圆是凸集,所以只要判断是否每个顶点都在圆内即可。
设两圆为O1,O2,半径分别为r1, r2,要判断O2是否在O1内。先比较r1,r2的大小,如果r1<r2则o2不可能在o1内;否则如果两圆心的距离大于r1 -="" font="" r2="" ,则o2不在o1内;否则o2在o1内。<="">
如果该线段平行于X轴(Y轴),则过点point作该线段所在直线的垂线,垂足很容易求得,然后计算出垂足,如果垂足在线段上则返回垂足,否则返回离垂足近的端点;如果该线段不平行于X轴也不平行于Y轴,则斜率存在且不为0。设线段的两端点为pt1和pt2,斜率为:k = ( pt2.y - pt1. y ) / (pt2.x - pt1.x );该直线方程为:y = k* ( x - pt1.x) + pt1.y。其垂线的斜率为 - 1 / k,垂线方程为:y = (-1/k) * (x - point.x) + point.y 。
联立两直线方程解得:x = ( k^2 * pt1.x + k * (point.y - pt1.y ) + point.x ) / ( k^2 + 1) ,y = k * ( x - pt1.x) + pt1.y;然后再判断垂足是否在线段上,如果在线段上则返回垂足;如果不在则计算两端点到垂足的距离,选择距离垂足较近的端点返回。
只要分别计算点到每条线段的最近点,记录最近距离,取其中最近距离最小的点即可。
如果该点在圆心,因为圆心到圆周任一点的距离相等,返回UNDEFINED。
连接点P和圆心O,如果PO平行于X轴,则根据P在O的左边还是右边计算出最近点的横坐标为centerPoint.x - radius 或 centerPoint.x + radius。如果PO平行于Y轴,则根据P在O的上边还是下边计算出最近点的纵坐标为 centerPoint.y -+radius或 centerPoint.y - radius。如果PO不平行于X轴和Y轴,则PO的斜率存在且不为0,这时直线PO斜率为k = ( P.y - O.y )/ ( P.x - O.x )。直线PO的方程为:y = k * ( x - P.x) + P.y。设圆方程为:(x - O.x ) ^2 + ( y - O.y ) ^2 = r ^2,联立两方程组可以解出直线PO和圆的交点,取其中离P点较近的交点即可。
对于两条共线的线段,它们之间的位置关系有下图所示的几种情况。图(a)中两条线段没有交点;图 (b) 和 (d) 中两条线段有无穷焦点;图 (c) 中两条线段有一个交点。设line1是两条线段中较长的一条,line2是较短的一条,如果line1包含了line2的两个端点,则是图(d)的情况,两线段有无穷交点;如果line1只包含line2的一个端点,那么如果line1的某个端点等于被line1包含的line2的那个端点,则是图(c)的情况,这时两线段只有一个交点,否则就是图(b)的情况,两线段也是有无穷的交点;如果line1不包含line2的任何端点,则是图(a)的情况,这时两线段没有交点。
![]()
设一条线段为L0 = P1P2,另一条线段或直线为L1 = Q1Q2 ,要计算的就是L0和L1的交点。
1. 首先判断L0和L1是否相交(方法已在前文讨论过),如果不相交则没有交点,否则说明L0和L1一定有交点,下面就将L0和L1都看作直线来考虑。
2. 如果P1和P2横坐标相同,即L0平行于Y轴
a) 若L1也平行于Y轴,
i. 若P1的纵坐标和Q1的纵坐标相同,说明L0和L1共线,假如L1是直线的话他们有无穷的交点,假如L1是线段的话可用"计算两条共线线段的交点"的算法求他们的交点(该方法在前文已讨论过);
ii. 否则说明L0和L1平行,他们没有交点;
b) 若L1不平行于Y轴,则交点横坐标为P1的横坐标,代入到L1的直线方程中可以计算出交点纵坐标;
3. 如果P1和P2横坐标不同,但是Q1和Q2横坐标相同,即L1平行于Y轴,则交点横坐标为Q1的横坐标,代入到L0的直线方程中可以计算出交点纵坐标;
4. 如果P1和P2纵坐标相同,即L0平行于X轴
a) 若L1也平行于X轴,
i. 若P1的横坐标和Q1的横坐标相同,说明L0和L1共线,假如L1是直线的话他们有无穷的交点,假如L1是线段的话可用"计算两条共线线段的交点"的算法求他们的交点(该方法在前文已讨论过);
ii. 否则说明L0和L1平行,他们没有交点;
b) 若L1不平行于X轴,则交点纵坐标为P1的纵坐标,代入到L1的直线方程中可以计算出交点横坐标;
5. 如果P1和P2纵坐标不同,但是Q1和Q2纵坐标相同,即L1平行于X轴,则交点纵坐标为Q1的纵坐标,代入到L0的直线方程中可以计算出交点横坐标;
6. 剩下的情况就是L1和L0的斜率均存在且不为0的情况
a) 计算出L0的斜率K0,L1的斜率K1 ;
b) 如果K1 = K2
i. 如果Q1在L0上,则说明L0和L1共线,假如L1是直线的话有无穷交点,假如L1是线段的话可用"计算两条共线线段的交点"的算法求他们的交点(该方法在前文已讨论过);
ii. 如果Q1不在L0上,则说明L0和L1平行,他们没有交点。 c) 联立两直线的方程组可以解出交点来 这个算法并不复杂,但是要分情况讨论清楚,尤其是当两条线段共线的情况需要单独考虑,所以在前文将求两条共线线段的算法单独写出来。另外,一开始就先利用矢量叉乘判断线段与线段(或直线)是否相交,如果结果是相交,那么在后面就可以将线段全部看作直线来考虑。需要注意的是,我们可以将直线或线段方程改写为ax+by+c=0的形式,这样一来上述过程的部分步骤可以合并,缩短了代码长度,但是由于先要求出参数,这种算法将花费更多的时间。
分别求与每条边的交点即可。
设圆心为O,圆半径为r,直线(或线段)L上的两点为P1,P2。
1. 如果L是线段且P1,P2都包含在圆O内,则没有交点;否则进行下一步。
2. 如果L平行于Y轴,
a) 计算圆心到L的距离dis;
b) 如果dis > r 则L和圆没有交点; c) 利用勾股定理,可以求出两交点坐标,但要注意考虑L和圆的相切情况。 3. 如果L平行于X轴,做法与L平行于Y轴的情况类似;
4. 如果L既不平行X轴也不平行Y轴,可以求出L的斜率K,然后列出L的点斜式方程,和圆方程联立即可求解出L和圆的两个交点;
5. 如果L是线段,对于2,3,4中求出的交点还要分别判断是否属于该线段的范围内。
点集Q的凸包(convex hull)是指一个最小凸多边形,满足Q中的点或者在多边形边上或者在其内。下图中由红色线段表示的多边形就是点集Q={p0,p1,...p12}的凸包。
![]()
现在已经证明了凸包算法的时间复杂度下界是O(n*logn),但是当凸包的顶点数h也被考虑进去的话,Krikpatrick和Seidel的剪枝搜索算法可以达到O(n*logh),在渐进意义下达到最优。最常用的凸包算法是Graham扫描法和Jarvis步进法。本文只简单介绍一下Graham扫描法,其正确性的证明和Jarvis步进法的过程大家可以参考《算法导论》。
对于一个有三个或以上点的点集Q,Graham扫描法的过程如下:
令p0为Q中Y-X坐标排序下最小的点
设 压p0进栈S 压p1进栈S 压p2进栈S for i ← 3 to m do while 由S的栈顶元素的下一个元素、S的栈顶元素以及pi构成的折线段不拐向左侧 对S弹栈 压pi进栈S return S;
此过程执行后,栈S由底至顶的元素就是Q的凸包顶点按逆时针排列的点序列。需要注意的是,我们对点按极角逆时针排序时,并不需要真正求出极角,只需要求出任意两点的次序就可以了。而这个步骤可以用前述的矢量叉积性质实现。
四、结语
尽管人类对几何学的研究从古代起便没有中断过,但是具体到借助计算机来解决几何问题的研究,还只是停留在一个初级阶段,无论从应用领域还是发展前景来看,计算几何学都值得我们认真学习、加以运用,希望这篇文章能带你走进这个丰富多彩的世界。
|
2012年7月31日 星期二
[轉] 計算幾何算法概覽
uva 10543 - Traveling Politician
Traveling Politician
Time Limit: 2 seconds
A politician from the Alliance of Conservative Monarchists (ACM) is campaigning for the next election. In order to guarantee his victory, he has to make at least k public speeches. He will give one speech every day. If he has to give several speeches in the same city, they cannot be on consecutive days because that would be unproductive. However, the politician believes that giving speech in one day's interval is not useless; for example, giving one speech on Monday and the next one in the same city on Wednesday is alright because after two days, the people will forget about his first speech and his second speech will have as much effect as the first one.
He is absolutely certain that he will win, so at the same time he is moving to the capital. This means that his first speech will be given in his hometown, and his last speech - in the capital city. He knows that his speech-giving abilities deteriorate when he is tired. So he does not want to give more speeches than he has to; k speeches will be enough to win. What is the minimum number of speeches he has to give in order to start in his hometown, end up in the capital and give at least k speeches (Including his speeches in his hometown and in the capital) on the way, without ever giving a speech in the same city on two consecutive days?
Input
The input will consist of several test cases. Each test case will begin with 3 integers on a line - n (the number of cities on the map), m (the number of roads connecting cities) and k (the minimum number of speeches). The next m lines will each contain 2 integers, u and v, meaning that the politician can visit city v immediately after visiting city u. All other routes of travel are infeasible from the point of view of his budget. The politician's hometown is city number 0, and the capital is city number n-1. You can assume that 2<=n<=50 and 2<=k<=16. Input is terminated by a line containing three zeroes.
The input will consist of several test cases. Each test case will begin with 3 integers on a line - n (the number of cities on the map), m (the number of roads connecting cities) and k (the minimum number of speeches). The next m lines will each contain 2 integers, u and v, meaning that the politician can visit city v immediately after visiting city u. All other routes of travel are infeasible from the point of view of his budget. The politician's hometown is city number 0, and the capital is city number n-1. You can assume that 2<=n<=50 and 2<=k<=16. Input is terminated by a line containing three zeroes.
Output
Print one line per test case, giving the minimum total number of speeches. If this is impossible to do, print "LOSER". See examples. If in a scenario the politician requires to give more than 20 speeches he should be considered a LOSER and so in that case you should print "LOSER" as well.
Print one line per test case, giving the minimum total number of speeches. If this is impossible to do, print "LOSER". See examples. If in a scenario the politician requires to give more than 20 speeches he should be considered a LOSER and so in that case you should print "LOSER" as well.
Sample Input | Sample Output |
3 3 3 0 1 0 2 1 2 5 6 5 0 1 0 3 1 2 2 4 3 2 3 4 3 3 10 0 1 1 0 1 2 0 0 0 | 3 LOSER 11 |
Problemsetter: Igor Naverniouk, special thanks to Shahriar Manzoor
A^n=A^(n-1)*A given you the a matrix where each entry denotes the number of way to reach the destination from the source with n length path.
uva 10116 - Robot Motion
Problem F: Robot Motion
Source file: | robot.{c, cpp, java, pas} |
Input file: | robot.in |
Output file: | robot.out |

N north (up the page)
S south (down the page)
E east (to the right on the page)
W west (to the left on the page)
For example, suppose the robot starts on the north (top) side of Grid 1 and starts south (down). The path the robot follows is shown. The robot goes through 10 instructions in the grid before leaving the grid.
Compare what happens in Grid 2: the robot goes through 3 instructions only once, and then starts a loop through 8 instructions, and never exits.
You are to write a program that determines how long it takes a robot to get out of the grid or how the robot loops around.
There will be one or more grids for robots to navigate. The data for each is in the following form. On the first line are three integers separated by blanks: the number of rows in the grid, the number of columns in the grid, and the number of the column in which the robot enters from the north. The possible entry columns are numbered starting with one at the left. Then come the rows of the direction instructions. Each grid will have at least one and at most 10 rows and columns of instructions. The lines of instructions contain only the characters N, S, E, orW with no blanks. The end of input is indicated by a row containing 0 0 0.
For each grid in the input there is one line of output. Either the robot follows a certain number of instructions and exits the grid on any one the four sides or else the robot follows the instructions on a certain number of locations once, and then the instructions on some number of locations repeatedly. The sample input below corresponds to the two grids above and illustrates the two forms of output. The word "step" is always immediately followed by "(s)" whether or not the number before it is 1.
Example input:
Example output:3 6 5 NEESWE WWWESS SNWWWW 4 5 1 SESWE EESNW NWEEN EWSEN 0 0 0
graph traversal10 step(s) to exit 3 step(s) before a loop of 8 step(s)
uva 10010 - Where's Waldorf?
Where's Waldorf?
Given a m by n grid of letters, ( Where's Waldorf? |

Input
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.The input begins with a pair of integers, m followed by n,


Output
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.For each word in the word list, a pair of integers representing the location of the corresponding word in the grid must be output. The integers must be separated by a single space. The first integer is the line in the grid where the first letter of the given word can be found (1 represents the topmost line in the grid, and m represents the bottommost line). The second integer is the column in the grid where the first letter of the given word can be found (1 represents the leftmost column in the grid, and n represents the rightmost column in the grid). If a word can be found more than once in the grid, then the location which is output should correspond to the uppermost occurence of the word (i.e. the occurence which places the first letter of the word closest to the top of the grid). If two or more words are uppermost, the output should correspond to the leftmost of these occurences. All words can be found at least once in the grid.
Sample Input
1 8 11 abcDEFGhigg hEbkWalDork FtyAwaldORm FtsimrLqsrc byoArBeDeyv Klcbqwikomk strEBGadhrb yUiqlxcnBjf 4 Waldorf Bambi Betty Dagbert
Sample Output
2 5 2 3 1 2 7 8
Miguel Revilla
2000-08-22
BFS
uva 10009 - All Roads Lead Where?
All Roads Lead Where?
There is an ancient saying that ``All Roads Lead to Rome''. If this were true, then there is a simple algorithm for finding a path between any two cities. To go from city A to city B, a traveller could take a road from A to Rome, then from Rome to B. Of course, a shorter route may exist. The network of roads in the Roman Empire had a simple structure: beginning at Rome, a number of roads extended to the nearby cities. From these cities, more roads extended to the next further cities, and so on. Thus, the cities could be thought of as existing in levelsaround Rome, with cities in the ith level only connected to cities in the i-1th and i+1th levels (Rome was considered to be at level 0). No loops existed in the road network. Any city in level i was connected to a single city in level i-1, but was connected to zero or more cities in level i+1. Thus, to get to Rome from a given city in level i, a traveller could simply walk along the single road leading to the connected i-1 level city, and repeat this process, with each step getting closer to Rome. Given a network of roads and cities, your task is to find the shortest route between any two given cities, where distance is measured in the number of intervening cities.All Roads Lead Where? |
Input
The first line is the number of test cases, followed by a blank line.The first line of each test case of the input contains two numbers in decimal notation separated by a single space. The first number (m) is the number of roads in the road network to be considered. The second number (n) represents the number of queries to follow later in the file. For each test case, in the next m lines of the input, each contain the names of a pair of cities separated by a single space. A city name consists of one or more letters, the first of which is in uppercase. No two cities begin with the same letter. The name Rome always appears at least once in this section of input, for each test case; this city is considered to be at level 0, the lowest-numbered level. The pairs of names indicate that a road connects the two named cities. The first city named on a line exists in a lower level than the second named city. The road structure obeys the rules described above. For each test case, no two lines of input in this section are repeated. The next n lines, for each test case in the input contain the names of a pair of cities separated by a single space. City names are as described above. These pairs of cities are the query pairs. Your task for each query pair is to find the shortest route from the first named city to the second. Each of the cities in a query pair is guaranteed to have appeared somewhere in the previous input section, for each test case, describing the road structure.Each test case will be separated by a single line.
Output
In each test case, for each of the n query pairs, output a sequence of uppercase letters indicating the shortest route between the two query pair cities. The sequence must be output as consecutive letters, without intervening whitespace, on a single line. For each test case, the first output line corresponds to the first query pair, the second output line corresponds to the second query pair, and so on. The letters in each sequence indicate the first letter of the cities on the desired route between the query pair cities, including the query pair cities themselves. A city will never be paired with itself in a query.Print a blank line between the outputs for two consecutive test cases.Sample Input
1 7 3 Rome Turin Turin Venice Turin Genoa Rome Pisa Pisa Florence Venice Athens Turin Milan Turin Pisa Milan Florence Athens Genoa
Sample Output
TRP MTRPF AVTG
Miguel Revilla
2000-08-22
SSSP -Dijastra
2012年7月30日 星期一
uva 10004 - Bicoloring
Bicoloring
In 1976 the ``Four Color Map Theorem" was proven with the assistance of a computer. This theorem states that every map can be colored using only four colors, in such a way that no region is colored using the same color as a neighbor region.Here you are asked to solve a simpler similar problem. You have to decide whether a given arbitrary connected graph can be bicolored. That is, if one can assign colors (from a palette of two) to the nodes in such a way that no two adjacent nodes have the same color. To simplify the problem you can assume:Bicoloring |
- no node will have an edge to itself.
- the graph is nondirected. That is, if a node a is said to be connected to a node b, then you must assume that b is connected to a.
- the graph will be strongly connected. That is, there will be at least one path from any node to any other node.
Input
The input consists of several test cases. Each test case starts with a line containing the number n ( 1 < n < 200) of different nodes. The second line contains the number of edges l. After this, l lines will follow, each containing two numbers that specify an edge between the two nodes that they represent. A node in the graph will be labeled using a number a (
Output
You have to decide whether the input graph can be bicolored or not, and print it as shown below.Sample Input
3 3 0 1 1 2 2 0 9 8 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0
Sample Output
NOT BICOLORABLE. BICOLORABLE.
Miguel Revilla
2000-08-21
BFS
uva 10000 - Longest Paths
Longest Paths
It is a well known fact that some people do not have their social abilities completely enabled. One example is the lack of talent for calculating distances and intervals of time. This causes some people to always choose the longest way to go from one place to another, with the consequence that they are late to whatever appointments they have, including weddings and programming contests. This can be highly annoying for their friends.Longest Paths |
César has this kind of problem. When he has to go from one point to another he realizes that he has to visit many people, and thus always chooses the longest path. One of César's friends, Felipe, has understood the nature of the problem. Felipe thinks that with the help of a computer he might be able to calculate the time that César is going to need to arrive to his destination. That way he could spend his time in something more enjoyable than waiting for César.
Your goal is to help Felipe developing a program that computes the length of the longest path that can be constructed in a given graph from a given starting point (César's residence). You can assume that the graph has no cycles (there is no path from any node to itself), so César will reach his destination in a finite time. In the same line of reasoning, nodes are not considered directly connected to themselves.
Input
The input consists of a number of cases. The first line on each case contains a positive number n (
After this, a second number s is provided, indicating the starting point in César's journey (


A pair of zeros (``0 0") indicates the end of the case.
As mentioned before, you can assume that the graphs provided will not be cyclic.
Output
For each test case you have to find the length of the longest path that begins at the starting place. You also have to print the number of the final place of such longest path. If there are several paths of maximum length, print the final place with smallest number.Print a new line after each test case.
Sample Input
2 1 1 2 0 0 5 3 1 2 3 5 3 1 2 4 4 5 0 0 5 5 5 1 5 2 5 3 5 4 4 1 4 2 0 0 0
Sample Output
Case 1: The longest path from 1 has length 1, finishing at 2. Case 2: The longest path from 3 has length 4, finishing at 5. Case 3: The longest path from 5 has length 2, finishing at 1.
Miguel Revilla
2000-08-21
DFS
uva 785 - Grid Colouring
Grid Colouring
A set of contours is represented on a two dimensional grid as illustrated in the sample below. The contours are made of any printable character different than space and `_' (underscore). In the sample this character is `X'. All the other points of the grid are represented by spaces and marking characters.Grid Colouring |
A grid zone is defined as the set of points enclosed within a closed contour such that any two zone points can be connected by a path which does not cross any contour and whose segments run vertically or horizontally. A zone is marked if it contains identical characters, called marking characters, different than space and the character used to draw the grid contours. No zone can contain different marking characters. However, observe that while all the contours are drawn with the same character, the markings of different zones can be different. A zone is unmarked if it contains only spaces. Any grid zone can be either marked or unmarked and the marking characters can appear inside grid zones only.
Write a program to fill all the marked zones on each grid read from the input file. A marked zone is filled with its marking character, as shown in the sample.
Input
On input, each grid is terminated by a separation line full of underscores `_'. There are at most 30 lines and at most 80 characters in a line for each grid. The lines can be of different length.Output
The standard output file contains the painted grids. Each grid is output in the same format it is read from the input file, including the separation line, blank lines and possible leading or trailing spaces.Sample Input
XXXXXXXXXXXXXXXXXXXX X X X X # # XXXXXXXX / X X X X XXXXXXXXXXXXXXXXXXXX _____________________________ XXXXXXXXXXXX XXXXXX X # XXX XXX X X X XX X X X X X X X XXXXXXX XXXXXXX X XX X X X XXXX XXXXXXXX XX XXXX X X / X X X X / X XXXXXXXXXXXXX XXXXXXXX _____________________________
Sample Output
XXXXXXXXXXXXXXXXXXXX X######X///////////X X######XXXXXXXX////X X#############X////X XXXXXXXXXXXXXXXXXXXX _____________________________ XXXXXXXXXXXX XXXXXX X###########XXX XXX X X X##XX#########X X X X X##X X##XXXXXXX XXXXXXX X###XX###X X#######X XXXX XXXXXXXX XX#####XXXX##X X//////X X###########X X//////X XXXXXXXXXXXXX XXXXXXXX _____________________________
Miguel Revilla
2001-01-05
Flood Fill
uva 762 - We Ship Cheap
We Ship Cheap
The We-Ship-Cheap package shipping company is always interested in reducing their costs. They have decided that a computerized shipping route planner that determines the shortest shipping route between two cities would speed package delivery. We-Ship-Cheap services a number of different cities. They have established direct shipping links between pairs of cities. It is somewhat unusual that they have been able to create all the direct links with exactly the same distance. Unfortunately, since not every pair of cities is connected by a direct link, the shortest shipping route often involves travel through multiple intermediate cities.We Ship Cheap |
Input and Output
Write a program that given a collection of cities and links between them, and a shipping request, prints out the shortest shipping route for the given shipping request.The program takes as input a variable number of lines, each consisting of exactly two cities (identified by a two-uppercase-letter code and separated by a space). Each line identifies a bidirectional link that exists between the two cities. Following the link information will be a single shipping request that identifies a source and destination city. The program will produce as output a shortest shipping route (note that multiple minimum length routes may exist) between the two cities. If no route exists, the program should output ``No route''
The first line of input will consist of a single integer that represents the number of links given in the input. The last line will contain the source and destination cities for which you are to find the minimal route. You may assume that the input is valid and consistent.
If there are two or more test cases, it will be a blank line between two consecutive, both in input and output files.
Sample input
3 JV PT KA PT KA HP JV HP 2 JV PT KA HP JV HP
Sample output
JV PT PT KA KA HP No route
Miguel Revilla
2000-12-30
Dijastra
uva 679 - Dropping Balls
Dropping Balls
A number of K balls are dropped one by one from the root of a fully binary tree structure FBT. Each time the ball being dropped first visits a non-terminal node. It then keeps moving down, either follows the path of the left subtree, or follows the path of the right subtree, until it stops at one of the leaf nodes of FBT. To determine a ball's moving direction a flag is set up in every non-terminal node with two values, either false or true. Initially, all of the flags are false. When visiting a non-terminal node if the flag's current value at this node isfalse, then the ball will first switch this flag's value, i.e., from the false to the true, and then follow the left subtree of this node to keep moving down. Otherwise, it will also switch this flag's value, i.e., from the true to the false, but will follow the right subtree of this node to keep moving down. Furthermore, all nodes of FBT are sequentially numbered, starting at 1 with nodes on depth 1, and then those on depth 2, and so on. Nodes on any depth are numbered from left to right.Dropping Balls |
For example, Fig. 1 represents a fully binary tree of maximum depth 4 with the node numbers 1, 2, 3, ..., 15. Since all of the flags are initially set to be false, the first ball being dropped will switch flag's values at node 1, node 2, and node 4 before it finally stops at position 8. The second ball being dropped will switch flag's values at node 1, node 3, and node 6, and stop at position 12. Obviously, the third ball being dropped will switch flag's values at node 1, node 2, and node 5 before it stops at position 10.

Fig. 1: An example of FBT with the maximum depth 4 and sequential node numbers.
Now consider a number of test cases where two values will be given for each test. The first value is D, the maximum depth of FBT, and the second one is I, the Ith ball being dropped. You may assume the value of I will not exceed the total number of leaf nodes for the given FBT.
Please write a program to determine the stop position P for each test case.
For each test cases the range of two parameters D and I is as below:

Input
Contains l+2 lines.Line 1 I the number of test cases Line 2test case #1, two decimal numbers that are separatedby one blank ... Line k+1
test case #k Line l+1
test case #l Line l+2 -1 a constant -1 representing the end of the input file
Output
Contains l lines.Line 1 the stop position P for the test case #1 ... Line k the stop position P for the test case #k ... Line l the stop position P for the test case #l
Sample Input
5 4 2 3 4 10 1 2 2 8 128 -1
Sample Output
12 7 512 3 255
Miguel Revilla
2000-08-14
binary tree traversal
uva 677 - All Walks of length "n" from the first node
All Walks of length n from the first node
All Walks of length n from the first node |
A computer network can be represented as a graph. Let G = (V, E) be an undirected graph, V =
represents all nodes, where m is the number of nodes, and E represents all edges. The first node is v1 and the last node is vm . The number of edges is k. Define the adjacency matrix
where



An example of the adjacency matrix and its corresponding graph are as follows:
![$\textstyle \parbox{.5\textwidth}{
\begin{displaymath}
\left [
\begin{array}{ccc...
...
1 & 0 & 1 & 0 & 1 \\
0 & 0 & 1 & 1 & 0
\end{array}\right ]
\end{displaymath}}$](http://uva.onlinejudge.org/external/6/677img4.gif)

Calculate


The following example shows the walks of length 2.
![\begin{displaymath}A^2 = A \cdot A =
\left [
\begin{array}{ccccc}
0 & 1 & 0 & 1 ...
...\
0 & 1 & 1 & 1 & 1 \\
1 & 1 & 1 & 1 & 1
\end{array}\right ]
\end{displaymath}](http://uva.onlinejudge.org/external/6/677img8.gif)
Write programs to do above calculation and print out all distinct walks of length n. (In this problem we let the maximum walks of length n be 5 and the maximum number of nodes be 10.)
Input
The input file contains a number of test examples, the test examples are separated by -9999. Each test example consists of the number of nodes and the length of walks in the first row, and then the adjacency matrix.Output
The output file must contain all distinct walks of the length n, and with all its nodes different, from the first node, listed in lexicographical order. In case there are not walks of length n, just print `no walk of length n'
Separate the output of the different cases by a blank line.
Sample Input
5 2 0 1 0 1 0 1 0 1 0 0 0 1 0 1 1 1 0 1 0 1 0 0 1 1 0 -9999 5 3 0 1 0 1 0 1 0 1 0 0 0 1 0 1 1 1 0 1 0 1 0 0 1 1 0
Sample Output
(1,2,3) (1,4,3) (1,4,5) (1,2,3,4) (1,2,3,5) (1,4,3,2) (1,4,3,5) (1,4,5,3)
Miguel Revilla
2000-08-14
BFS on graph
訂閱:
文章 (Atom)