ZOL 3977. Pointers

简介:   太久没有做 zoj,对 oj 来说,由于它高度的”黑盒性“(输入数据和答案完全保密),保护自信心是非常重要的。所以我先选择一道非常简单的题目刷起。本题目是一个相当简单的题目,难度系数和求 A+B 相当。

  太久没有做 zoj,对 oj 来说,由于它高度的”黑盒性“(输入数据和答案完全保密),保护自信心是非常重要的。所以我先选择一道非常简单的题目刷起。本题目是一个相当简单的题目,难度系数和求 A+B 相当。

  本题,已知一个指针,初始状态指向 N(北),现在对指针做一系列顺时针(C)或者逆时针(A)旋转 90 度的操作,问指针然后指向哪个方向。

  由于四个方向形成一个循环,所以很自然的提示出,把四个方向所在的”圆环“展开成一个数组,所有的旋转操作实际上是移动数组内的索引,对索引进行递增或者递减的操作。然后对索引进行对数组长度的 MOD (取余)操作,限制在合理范围内即可。

  设索引值为 x,初始值为 0,定义向逆时针方向旋转定义为正方向,则:

  逆时针(A)旋转 90 度:x = ( x + 1 )  % 4;

  顺时针(C)选择 90 度:x = ( x - 1 + 4 ) % 4 = ( x + 3 ) % 4;

  因此,我们需要把旋转方向(A 或 C),映射到对 x 的递增值(1 或 3 )上。因此我们发现这里有一个巧合:A 和 C 之间的差值(C - A = 2),恰好也是这个递增值之间的差值( 3 - 1 = 2)。所以这个映射关系,不需要使用条件判断,可以直接写出此映射关系:

  x = ( x + *p - 'A' + 1 ) % 4; ( *p = 'A' 或 'C' )

  如果我们进一步查阅一下 ASCII 码表,上面的代码也等效于:

  x = ( x + *p - '@' ) % 4; 或者  x = ( x + *p - 0x40 ) % 4;

  最终代码如下:

#include <stdio.h>
int main(int argc, char* argv[])
{
    int i, x, count = 0;
    char *p;
    char directions[8] = "NWSE";
    char line[128];
    scanf("%d\n", &count);
    for(i = 0; i < count; i++)
    {
        gets(line);
        p = line;
        x = 0;
        while(*p)
        {
            x = (x + (*p - 'A' + 1)) & 3;
            ++p;
        }
        printf("%c\n", directions[x]);
    }
    return 0;
}

 

  【补充】由于旋转次数很少(不超过 100 次),因此如果我们一直对 x 进行累加,也不会溢出 int 的最大值。所以在 while 循环中的 MOD 操作可以去除,仅在最后输出结果时,对 x 进行一次 MOD 操作即可。

目录
相关文章
|
1月前
|
算法 安全 C++
C++ Effective Modern Pointer (智能指针模块)
C++ Effective Modern Pointer (智能指针模块)
|
1月前
|
小程序 JavaScript
Avoid mutating a prop directly since the value will be overwritten whenever the parent comp
Avoid mutating a prop directly since the value will be overwritten whenever the parent comp
A - MaratonIME stacks popcorn buckets
A - MaratonIME stacks popcorn buckets
|
C++
C++中的智能指针(smart pointer)
C++中的智能指针(smart pointer)
116 0
LeetCode 116. Populating Next Right Pointers
给定一颗二叉树,填充每一个节点的next指针使其指向右侧节点。 如果没有下一个右侧节点,则下一个指针应设置为NULL。
66 0
LeetCode 116. Populating Next Right Pointers
How to assign free areas? | Operating system principle
How to assign free areas? | Operating system principle
46 0
relocation R_X86_64_PC32 against symbol can not be used when making a shared object recompile with
relocation R_X86_64_PC32 against symbol can not be used when making a shared object recompile with
520 0
can not be used when making a shared object; recompile with -fPIC
can not be used when making a shared object; recompile with -fPIC
245 0
|
安全 Shell
【C++11】Smart Pointer 智能指针
首先看一个下面的栗子,左边是木有使用智能指针的情况,当执行foo()函数,其中的e指针会在bar(e)时传入bar函数,但是在bar函数结束后没有人为delete e时,就会导致内存泄漏;但是在右边的栗子中,使用了unique_ptr智能指针(single ownership),就能防止内存泄漏。
178 0
【C++11】Smart Pointer 智能指针
why SpringComponentScanServer is needed
why SpringComponentScanServer is needed
76 0
why SpringComponentScanServer is needed