• 小米兔跳格子 (dfs BFS/ 贪心)


    原题链接:https://code.mi.com/problem/list/view?id=119
    描述
    米兔爸爸为了让小米兔好好锻炼身体,便给小米兔设置了一个挑战——跳格子。
    要吃到自己心爱的胡萝卜,小米兔需要跳过面前一些格子。现有
    NN
    N 个格子,每个格子内都写上了一个非负数,表示当前最多可以往前跳多少格,胡萝卜就放在最后一个格子上。米兔开始站在第 1 个格子,试判断米兔能不能跳到最后一个格子吃到胡萝卜呢?
    输入

    输入为
    NN
    N 个数字 (
    N<10N lt 10
    N<10),用空格隔开,第
    ii
    i 个数字
    sis_i
    s
    i

    (
    0≤si<10 0 le s_i lt 10
    0≤s
    i

    <10) 表示米兔站在第
    ii
    i 个格子上时,最多能往前跳的格数。

    输出

    若米兔能跳到最后一个格子上吃到胡萝卜,输出 “true“,否则输出 “false“

    输入样例
    2 0 1 0 0 3 4
    复制样例
    输出样例
    false

    贪心:

    #include <iostream>
    const int N=100;
    using namespace std;
    int a[N];
    int mp[N];
    int cnt=0;
    int main()
    {
        int g;
        char c;
        while(cin>>g){
            a[++cnt]=g;
            c=cin.get();
            if(c!=' ') break;
        }
        mp[1]=1;
        for(int i=1;i<=cnt;i++){
            if(mp[i]==1)
                for(int j=1;j<=a[i];j++){
                    if(i+j<=cnt) mp[i+j]=1;
                }
        }
        //cout << "Hello world!" << endl;
        return 0;
    }
    

    DFS:

    #include <iostream>
    const int N=100;
    using namespace std;
    int a[N];
    int mp[N];
    int cnt=0;
    bool dfs(int now){
        if(now==cnt) return true;
        for(int i=1;i<=a[now];i++){
            if(i+now<=cnt&&dfs(i+now)) return true;
        }
        return false;
    }
    int main()
    {
        int g;
        char c;
        while(cin>>g){
            a[++cnt]=g;
            c=cin.get();
            if(c!=' ') break;
        }
        if(dfs(1)) cout<<"true"<<endl;
        else cout<<"false"<<endl;
        //cout << "Hello world!" << endl;
        return 0;
    }
    

    BFS

    #include <iostream>
    #include <bits/stdc++.h>
    const int N=20;
    using namespace std;
    int a[N];
    bool bfs(int n){
        queue<int> q;
        q.push(1);
        while(!q.empty()){
            int now=q.front();q.pop();
            if(now==n) return true;
            for(int i=1;i<=a[now];i++) q.push(now+i);
        }
        return false;
    }
    int main()
    {
        int n;
        int cnt=0;
        char c;
        //cin>>n;
        while(cin>>n){
            c=cin.get();
             a[++cnt]=n;
            if(c!=' ') break;
        }
        //for(int i=1;i<=cnt;i++) cin>>a[i];
        if(bfs(cnt)) puts("true"); else puts("false");
        //cout << "Hello world!" << endl;
        return 0;
    }
    
  • 相关阅读:
    centos7安装nginx
    linux经常使用的命令
    linux 安装 VNC
    linux配置yum源
    docker服务器、以及容器设置自动启动
    docker初步学习以及常用命令
    Docker命令详解(run篇)
    Linux scp命令
    Linux常用命令学习31个
    Linux下解压tar.xz文件
  • 原文地址:https://www.cnblogs.com/-yjun/p/10629896.html
Copyright © 2020-2023  润新知