51Nod 1941 找宝藏 c/c++题解

题目描述

在一片平坦的大草原上,现在你站在一棵大树下,宝藏地图上面有一些指令,会叫你向东,西,南,北方向走若干步,最终你所站的位置就是宝藏的位置。每次只能向东,西,南,北走动,请问至少要走几步能够到达宝藏,假设这片草原都是平坦的无障碍物的。
输入
单组测试数据。
输入占一行,给出一个指令字符串,最多是200个字符。指令通过逗号分开,每一个指令由两部分组成,一个是正整数(不超过1000),以及一个方向(N (北), E (东), S (南),W (西))。比如3W 表示向西走3步。字符串的最后有一个’.'表示指令结束。
输出
输出一个整数,表示最少需要的步数。
输入样例
样例输入1
3N,1E,1N,3E,2S,1W.
输出样例
样例输出1
5

题解:

这道题千万不要想复杂了(刚一开始我以为是要求最短路…),设置初始位置为x=0,y=0,只需要按照输入的指令一步步的走(也就是x,y坐标不断变化),最后最少的步数就是abs(x)+abs(y)(这里不难想到吧,比如起点(0,0)到终点(-3,3),最短的距离就是3+3)
然后就是指令的读取需要细心一下,算了,直接看注释吧。

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
string str;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    while(cin >> str)
    {
        int x,y,i;
        x = y = i = 0;
        while(1)
        {
        .	/**
        		从i位置开始截取字符串,直到遇到','或者'.'
        		如果是后者,循环最后会有判断,那直接退出循环即可
        		如果是前者,i++,继续读取下一个指令
        	*/
            string tmp_str;
            while(str[i] != ',' && str[i] != '.')
            {
                tmp_str += str[i];
                i++;
            }
            int len = tmp_str.length();
            int num = stoi(tmp_str.substr(0,len-1));// 比如这个指令为tmp_str = "123N",那么len-1=3,substr()可以直接从0下标开始截取3个长度的字符串"123",然后将字符串用stoi()转换为int型即可
            char dir = tmp_str[len-1];// len-1下标位置对应的字符就是方向
            //printf("本次移动:\n初始位置: (%d,%d)\nnum = %d dir = %c\n",x,y,num,dir);
            if(dir == 'N')
            {
                y += num;
            }
            else if(dir == 'E')
            {
                x += num;
            }
            else if(dir == 'S')
            {
                y += -num;
            }
            else if(dir == 'W')
            {
                x += -num;
            }
            //printf("本次移动后:\n位置: (%d,%d)\n",x,y);
            /** 判断是不是到了末尾 */
            if(str[i] == '.')
                break;
            else
                i++;
        }
        int min_step = abs(x) + abs(y);
        cout << min_step << endl;
    }
    return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值