华为OD机试-找终点

该程序在C++环境中运行,通过在线编译器处理输入的数字序列。它使用自定义的搜索函数`search`,从数组中寻找特定模式,返回步长。程序首先将带空格的字符串输入转换为整数数组,然后对数组的一半长度进行遍历,寻找满足条件的搜索路径长度。如果找不到符合条件的路径,则返回-1。
摘要由CSDN通过智能技术生成
// Online C++ compiler to run C++ program online
#include<iostream>
#include<vector>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<exception> 
#include<map>
#include<cmath>
#include<unordered_map>
#include<set>
#include<climits>
#include<ctype.h>
#include<queue>
#include<stack>
#include<list>
#include<regex>
using namespace std;

int search(int idx, int step, const vector<int>& list)
{
    if (idx == (list.size() - 1))
        return step;

    if (idx >= list.size())
        return -1;

    return search(idx + list[idx], step + 1, list);
}

int main() {
    //输入处理
    string str;
    // 带空格的字符串输入
    getline(cin, str);

    //空格分割
    vector<int> list;
    str += " ";
    while (str.find(" ") != string::npos) {
        int found = str.find(" ");
        list.push_back(atoi(str.substr(0, found).c_str()));
        str = str.substr(found + 1);
    }

    int ret = INT_MAX;
    int len = list[0] / 2;
    for (int i = 1; i < len; ++i)
    {
        int val = search(i, 1, list);
        if (val < 0)
            continue;

        if (val < ret)
            ret = val;
    }

    if (ret == INT_MAX)
    {
        ret = -1;
    }

    cout << ret;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值