ACM UVa算法题209 Triangular Vertices的解法

Uva编程经验:C++算法代码集合 Uva在线评判系统是一种为计算机编程竞赛而设计的网络平台,它允许参赛者提交代码并自动运行在多个测试用例上,以此来测试代码的正确性和效率。该系统广泛用于ACM国际大学生程序设计竞赛(ICPC)、区域竞赛以及个人练习等多种场合。 阅读详情

有一段时间没有做ACM算法题目了,今天正好有空便随便挑了209题来做做:ACM UVa算法题#209题

这道题有几个要点:

1.   给定坐标系

坐标系很容易定,我采用的是第一个点为(0, 0)点,X方向差别为2个单位,Y方向差别为1个单位,点之间的距离,也就是LEN为1个单位,这样便于计算。注意我用的不是实际长度,而是抽象的单位,这个单位在不同方向上面意义不一样,否则很容易通过三角形相关公理推出这样的三角形不存在,我们关心的只是这样的一个对应关系。这里的人为设定确实有些Confusing,我之前也是按照一般的三角形的长度,如3,4,5来定义,但是后来发现这样做做的乘除法太多,过于浪费CPU Cycle,如果按照我这样的设定,大部分情况只用到加减法,另外一种情况只需用到移位操作即可。

参看下图:

2.   判断是否两点连线是一条边(Coincide)

这里可以分两种情况:

a.   Y1 = y2, 必然是Coincide

b.   否则,X_Delta = abs(x1 – x2), Y_Delta = abs(y1 – y2), 由于之前我们人为设定X方向差别为2个单位,Y方向差别为1一个单位,因此只要X_Delta = Y_Delta即可

 

3.   计算距离

假定是Coincide的情况,否则直接返回出错,因为在非Coincide的情况无需计算距离。此外,由于这里已经知道是Coincide,并且我们并没有统一单位,所以这里不能也不应该用勾股定理来计算长度,而是采用比例的方法,同样分两种情况,参考上图:

a.   Y1 = y2, 那么因为X方向上两个单位对应一个长度Unit,所以长度=abs(x1 – x2) >> 1;

b.   否则,长度Unit的个数和X/Y方向(任意)的差别相等,也就是长度=abs(x1 – x2)

 

4.   判断是否是目标图形,并且每条边相等

对于三角形,很简单,直接对3条边判断即可,没有什么变数。对于四边形和六边形就不同了,需要用到遍历来确定一个从某点开始(我们可以固定为第一个点)遍历所有点最后回到该点的环,并且每条边长度均相等,注意这里由于题目的特殊性,不用判断平行等条件。可以用一个邻接矩阵来代表对应的边的长度,这个应该一次性计算出来,如果非Coincide则设置为某个特殊值,比如0

刚开始提交的时候,Rank是45,之后我又做了下面的优化:

1.   当遍历尝试完毕从最初点出发的某条边的时候,说明这一边不可能成为环,将其置为0表示不可通,并且遍历从最初点出发的其他同样长度的边,置为0,减少遍历次数

2.   在初始化计算所有点的坐标的时候改变了一点点算法,用加减法代替乘法

3.   最初坐标采用的是实际的长度,而不是像上面那样用不同的抽象单位算出,修改之后减少了大量乘除法计算

4.   调整遍历算法,由于从初始点出发之后,后3个点必然不能是初始点,因此做了一点修改对这个情况作了优化

5.   修改对邻接矩阵的算法,由于adj[i][j] = adj[j][i],所以只需计算矩阵的一半即可

修改之后再提交Rank变成了33,似乎是目前个人的最好纪录 J

32

0.170

792

 LittleJohn Yo

C

2002-02-04 07:02:47

732386

33

0.172

1160

 Yi Zhang

C++

2007-05-02 16:05:54

5551868

34

0.174

404

 Rodrigo Malta Schmidt

C

2001-08-30 08:46:54

539862

 
代码如下:
//  
//  ACM UVa Problem #209
//   http://acm.uva.es/p/v2/209.html
//
//  Author:  ATField
//  Email:   atfield_zhang@hotmail.com
//

#include 
< stdio.h >
#include 
< stdlib.h >
#include 
< string .h >

#define  MAX    65535

struct  point
{
public :
    
bool is_coincide(const point &pt) const
    
{
        
// not allow testing points with same coordinates
        if( _x == pt._x && _y == pt._y )
            
return false;

        
if( _y == pt._y )
            
return true;
        
else
        
{
            
int k1 = abs( _x - pt._x );
            
int k2 = abs( _y - pt._y );

            
if( k1 == k2 )
                
return true;
        }


        
return false;
    }


    
int get_dist(const point &pt) const
    
{
        
// not allow testing points with same coordinates
        if( _x == pt._x && _y == pt._y )
            
return 0;

        
if( _y == pt._y )
            
return abs(_x - pt._x) >> 1;        // need to divide by 2
        else
        
{
            
int k1 = abs( _x - pt._x );
            
int k2 = abs( _y - pt._y );

            
if( k1 == k2 )
                
return k1;
        }


        
return 0;
    }


public :
    
static const int X_DELTA = 2;
    
static const int Y_DELTA = 3;
    
static const int LEN = 4;

public :
    
int        _x;
    
int        _y;
    
int     _valid;

private :
    
static point s_all_points[MAX];

public :
    
static void prepare()
    
{
        
int level = 0;
        
int before_next_level = 1;
        
int next_x = 0;
        
int next_y = 0;

        
for( int i = 1; i < MAX ; ++i )
        
{
            s_all_points[i]._x 
= next_x;
            s_all_points[i]._y 
= next_y;
            before_next_level
--;

            
if( before_next_level == 0 )
            
{
                level
++;
                before_next_level 
= level + 1;
                next_x 
= -level;
                next_y
++;
            }

            
else
                next_x 
+= 2;

        }



    }


    
static point *all_points()
    
{
        
return s_all_points;
    }

}
;

point point::s_all_points[MAX];

bool  check_triangle( int   * n)
{
    
// 1. Duplicates
    
// No need to check duplicate because the following checks will do

    
// 2. Coincide
    
// Check every edge
    point *points = point::all_points();
    
if( points[n[0]].is_coincide(points[n[1]]) &&
        points[n[
0]].is_coincide(points[n[2]]) &&
        points[n[
1]].is_coincide(points[n[2]]) )
    
{
        
// 3. Same length
        
// Check every edge
        int len = points[n[0]].get_dist(points[n[1]]);
        
if( len == points[n[0]].get_dist(points[n[2]]) &&
            len 
== points[n[1]].get_dist(points[n[2]]) )
            
return true;
    }


    
return false;
}



bool  init_adj( int   * n,  int  num,  int  adj[ 6 ][ 6 ])
{
    point 
*points = point::all_points();

    
for( int i = 0; i < num; ++i )
    
{
        
for( int j = i; j < num; ++j )
        
{
            
if( i == j )
            
{
                adj[i][j] 
= 0;
                adj[j][i] 
= 0;
            }

            
else
            
{
                
// 1. Duplicates
                
// Return false when found duplicate
                if( n[i] == n[j] )
                    
return false;

                
// 2. Coincide & Len (When not coincide, len = 0)
                adj[i][j] = points[n[i]].get_dist(points[n[j]]);
                adj[j][i] 
= adj[i][j];
            }

        }

    }

        

    
return true;
}


int  find_same_len_loop( int  adj[ 6 ][ 6 ],  int  num)
{
    
int stack[6];
    
int used[6];
    
int next[6];

    
for( int i = 1; i < num; ++i )
    
{         
        
int len = adj[0][i];

        
// skip non-connected dots
        if( len == 0 ) continue;

        
// initialize "used" array & "next" array
        for( int j = 0; j < num; ++j )
        
{
            used[j] 
= 0;
        }
        
        
        
int top = 0;
        stack[
0] = i;
        used[i] 
= 1;
        next[
0] = -1;

        top
++;

        
while( top > 0 )
        
{
            next[top
-1]++;

            
// checked all the connected points?
            if( next[top-1] >= num )
            
{
                
// yes, then pop the stack
                top--;
                used[stack[top]] 
= 0;
            }

            
else
            
{
                
int next_point = next[top-1];

                
// follow non-used, same-length edge
                if( used[next_point] == 0 && len == adj[stack[top-1]][next_point] )
                
{
                    stack[top] 
= next_point;
                    used[next_point] 
= 1;

                    
// don't allow pushing 0 into stack before the last point
                    if( top < num - 1 ) 
                        next[top] 
= 0;
                    
else
                        next[top] 
= -1;

                    top
++;

                    
// stack is full? found a loop
                    if( top == num )
                        
return len;
                }

            }

        }


        
// if this doesn't work, delete all edges starting from id 0 of this len
        for( int j = i; j < num; ++j )
            
if( adj[0][j] == len )
                adj[
0][j] = 0;
    }


    
return 0;
}


bool  check_parallelogram( int   * n)
{
    
int adj[6][6];
    
if(!init_adj(n, 4, adj))
        
return false;           // found duplicate

    
if(find_same_len_loop(adj, 4))
        
return true;

    
return false;
}


bool  check_hexagon( int   * n)
{
    
int adj[6][6];
    
if(!init_adj(n, 6, adj))
        
return false;           // found duplicate

    
if(find_same_len_loop(adj, 6))
        
return true;

    
return false;
}


int  main( int  argc,  char   * argv[])
{
    point::prepare();
    
    
while(1)
    
{
        
char input[255];
        
if( gets(input) == NULL )
            
break;
        
else if( strlen(input) == 0 )
            
break;
        
        
int n[6];
        
int fields = sscanf( input, "%d %d %d %d %d %d", &n[0], &n[1], &n[2], &n[3], &n[4], &n[5] );

        printf(
"%s ", input);                    

        
switch(fields)
        
{
            
case 3:
                
{
                    
bool is_triangle = check_triangle(n);

                    
if( is_triangle )
                    
{
                        puts(
"are the vertices of a triangle");
                        
continue;
                    }


                    
break;
                }


            
case 4:
                
{
                    
bool is_parallelogram = check_parallelogram(n);

                    
if( is_parallelogram )
                    
{
                        puts(
"are the vertices of a parallelogram");
                        
continue;
                    }


                    
break;
                }


            
case 6:
                
{
                    
bool is_hexagon = check_hexagon(n);

                    
if( is_hexagon )
                    
{
                        puts(
"are the vertices of a hexagon");
                        
continue;
                    }


                    
break;
                }

        }


        puts(
"are not the vertices of an acceptable figure");

    }


    
return 0;
}


UVA算法竞赛示例代码深度解析 UVA(UVa Online Judge)是一个著名的在线算法竞赛平台,提供了一个庞大的题库,覆盖了从基础到高级各种难度的算法题目。通过提交代码,算法竞赛的参与者可以检验自己的算法设计与实现能力,并获得即时反馈。UVA适合初学者提升算法水平,同时也为专业人士提供了一个展示自己才能的舞台。在编程与算法的世界里,数据结构是构建算法与程序的基本要素。它们不只是简单地存储数据,还要能高效地处理数据。数组、链表、栈、队列、树和图是六种基础且广泛使用于算法竞赛中的数据结构。 阅读详情

相关推荐

基于MATLAB/Simulink与WSL2的ROS2实时联合仿真实践

本文详细介绍了基于MATLAB/Simulink与WSL2的ROS2实时联合仿真实践。通过环境配置、PX4仿真环境搭建、自定义消息生成、Simulink通信实现及实时优化等步骤,提供了完整的无人机位置控制案例,帮助开发者实现高精度的实时联合仿真。

red88的博客 204

UVA 算法竞赛入门 GettingStarted 解题报告 (下)

AOAPC I: Beginning Algorithm Contests (Rujia Liu) :: Volume 0. Getting Started 490 - Rotating Sentences 题:把输入90度旋转。如下所示: abcd      efg        转化为 ea fb gc  d 解: 1)获取每一行输入字符串,存入vecto

比尔的专栏 355

html一号店项目代码,项目一号店素材(html模板)

【实例简介】【实例截图】【核心代码】oneShop├── css│ ├── ShopShow.css│ ├── base.css│ ├── load.css│ ├── logo.css│ ├── register.css│ └── style.css├── detail.html├── images│ ├── Thumbs.db│ ├── a_close.png│...

weixin_35390150的博客 4991

uva算法入门经典题解导航 - Volume 1. Elementary Problem Solving - String

Title Total Submissions / Solving % Total Users / Solving % 401 - Palindromes 46239 25.06% 11065 76.67% 10010 - Where's Waldorf? 25362 28.10

追随大神的脚步~ 1035

[逆向实战] 淘宝x5sec滑条验证码slidedata参数逆向与自动化过码方案

本文详细解析了淘宝x5sec滑条验证码的核心参数slidedata的生成机制与逆向过程,提供了Python自动化过码方案。通过分析滑动轨迹加密流程、还原AES加密算法,并设计人类行为模拟轨迹,帮助开发者有效绕过淘宝滑块验证,适用于爬虫开发与自动化测试场景。

weixin_30851867的博客 739

TwinCAT3 主站动态配置 PDO 的实战技巧与性能优化

本文深入探讨了TwinCAT3主站动态配置PDO的实战技巧与性能优化策略。通过对比静态PDO的局限,阐述了动态配置在提升系统灵活性、降低网络负载和保障实时性方面的核心优势。文章提供了从环境准备、代码实现到错误排查的完整流程,并重点解析了PDO映射、SDO通道区别以及分布式时钟同步等关键概念,帮助工程师掌握EtherCAT网络性能调优的核心方法。

weixin_29213525的博客 347

UVa400 算法竞赛入门经典 刘汝佳

#include&lt;stdio.h&gt; #include&lt;string&gt; #include&lt;algorithm&gt; #include&lt;vector&gt; #include&lt;iostream&gt; #include &lt;iomanip&gt; using namespace std; vector&lt;string&gt;Vstr; voi

眼里一片海 421

使用xlwings在Python中对Excel表格进行操作是非常方便的,可以实现自动化处理、批量数据处理等功能

使用xlwings在Python中对Excel表格进行操作是非常方便的,可以实现自动化处理、批量数据处理等功能。本篇文章主要介绍如何使用xlwings对Excel表格进行多行多列数据设置和操作,并给出相应的源代码。接着,我们可以对这个范围内的所有单元格进行操作,如设置字体颜色、填充颜色、对齐方式等。以上就是使用xlwings对Excel表格进行多行多列数据操作和设置字体颜色、填充色和对齐方式的全部内容。最后,我们可以将数据写入到单元格中,也可以从单元格中读取数据。在Excel中,可以通过。

BUG?不存在的! 716
上一篇: 另一道看上去很吓人的面试题:如何交换a和b两个整数的值,不用额外空间 (Rev. 2)
下一篇: 我的MSDN Blog正式开张,欢迎大家访问 [ http://blogs.msdn.com/yizhang/ ]
ATField
博客等级 码龄25年 673粉丝 119原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值