5 条题解
-
0
Guest
-
0
嗨嗨嗨来发个题解先写头文件#include<bits/stdc++.h> #define maxp 2e5+10 using namespace std;
这道题我用的是记忆化搜索和BFS,那就建一个记忆化数组和一个队列
int p,a[maxp]; queue<int>Q;
下面这个函数来判断数据是否越界以及是否已经搜索过了
bool check(int t){ if(t>0&&t<=200000&&a[t]==0) return 1; return 0; }
接着开始求每个数需要的步数 首先3和5只需要一步,即a[3]=a[5]=1,其他数如果算过了即a[t]!=0就不用重复计算,没算过的等于他前一步的数值加1 比如在其中算到a[12]=4时,此时a[7]=3,a[9]=3,a[15]=3,a[17]=0,向前后走3或5步,a[7]a[9]a[15]都不等于零不用管,a[17]等于零,那么a[17]=a[12]+1
void build(){ a[3]=a[5]=1; Q.push(3); Q.push(5); while(!Q.empty()){ int t=Q.front(); if(check(t+3)){ a[t+3]=a[t]+1; Q.push(t+3); } if(check(t+5)){ a[t+5]=a[t]+1; Q.push(t+5); } if(check(t-3)){ a[t-3]=a[t]+1; Q.push(t-3); } if(check(t-5)){ a[t-5]=a[t]+1; Q.push(t-5); } Q.pop(); } return; }
此时所有数需要的步数都有了直接提出来就行了
int main() { build(); cin>>p; cout<<a[p]<<"\n"; return 0; }
你们最喜欢的完整代码来啦#include<bits/stdc++.h> #define maxp 2e5+10 using namespace std; int p; int a[maxp]; queue<int>Q; bool check(int t){ if(t>0&&t<=200000&&a[t]==0) return 1; return 0; } void build(){ a[3]=a[5]=1; Q.push(3); Q.push(5); while(!Q.empty()){ int t=Q.front(); if(check(t+3)){ a[t+3]=a[t]+1; Q.push(t+3); } if(check(t+5)){ a[t+5]=a[t]+1; Q.push(t+5); } if(check(t-3)){ a[t-3]=a[t]+1; Q.push(t-3); } if(check(t-5)){ a[t-5]=a[t]+1; Q.push(t-5); } Q.pop(); } return; } int main() { build(); cin>>p; cout<<a[p]<<****"\n"; return 0; }
完结撒花 QwQ~~~
- 1
信息
- ID
- 906
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 9
- 标签
- (无)
- 递交数
- 143
- 已通过
- 7
- 上传者