2.4日总结

第一题:选数

题解:思路还是很简单的,只需要想清楚dfs里的函数都是什么就可以了,还有一个简单的判断素数的函数,这题真没啥难度,就是属于基础题吧,请看AC代码

cpp 复制代码
#include <stdio.h>
#include <string.h>
#include <math.h>
int n,k,count;
int a[25];
int su(int n)
{
    for(int i=2;i<=sqrt(n);i++)
    {
        if(n%i==0)
        {
            return 0;
        }
    }
    return 1;
}
void dfs(int t,int sum,int index)
{
    if(t==k)
    {
        if(su(sum)&&sum!=0)
        {
            count++;
        }
        return ;
    }
    int flag=sum;
    for(int i=index;i<n;i++)
    {
        sum=flag+a[i];
        dfs(t+1,sum,i+1);
    }
    return ;
}
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    dfs(0,0,0);
    printf("%d\n",count);
    return 0;
}

第二题:奇怪的电梯

题解:这题看到最少按几次按钮,直接BFS就可以,但是我们的判断条件,需要加上是否本来就在当前层,或者说,层数是否在合法范围

cpp 复制代码
#include <stdio.h>

int n, a, b;
int p[501];
int book[501];
struct que
{
    int z;
    int step;
} q[1001];

int bfs()
{
    int hh=0,tt=1;
    int f=0;
    q[1].z=a;
    q[1].step=0;
    while(hh<tt)
    {
        hh++;
        for(int i=1;i<=2;i++)
        {
            if(i==1)
            {
                f=q[hh].z+p[q[hh].z];//下一层能走到哪
                if(f>0&&f<=n&&book[f]==0)
                {
                    book[f]=1;
                    tt++;
                    q[tt].z=f;
                    q[tt].step=q[hh].step+1;
                    if(f==b)
                    {
                        return q[tt].step;
                    }
                }
            }
            if(i==2)
            {
                f=q[hh].z-p[q[hh].z];//下一层能走到哪
                if(f>0&&f<=n&&book[f]==0)
                {
                    book[f]=1;
                    tt++;
                    q[tt].z=f;
                    q[tt].step=q[hh].step+1;
                    if(f==b)
                    {
                        return q[tt].step;
                    }
                }
            }
        }
    }
    return -1;
}
int main()
{
    scanf("%d%d%d", &n, &a, &b);
    if(a==b)
    {
          printf("0\n");
          return 0;
    }
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &p[i]);
    }
    int t = bfs();
    printf("%d\n", t);
    return 0;
}
相关推荐
Navigator_Z6 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH7 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶7 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
雪落漂泊8 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
LabVIEW开发10 小时前
LabVIEW 连接板:28 个端子怎么排,优先级怎么定
java·算法·labview
严肃小白兔11 小时前
MATLAB 数值计算中的精度与误差问题:浮点运算、误差传播与数值稳定性
人工智能·算法·matlab
青少儿编程课堂12 小时前
蓝桥杯青少组图形化省考报名倒计时·全国青少年信息素养大赛·电子学会图形化考级:校园黑白棋人机对战解析
c++·python·算法·bfs·信息学竞赛
jktantan13 小时前
注解式脱敏:用 Jackson 的 ContextualSerializer 做字段级策略(一)
spring boot·后端·算法·spring cloud·系统架构
Dream it possible!1 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划