<蓝桥杯>第十届省赛B组c/c++真题和部分题解
试题A:组队
这一题答案是490
试题B:年号字串
这一题答案是BYQ
2019 % 26 = 77 余 17 ,17 对应 Q
77 % 26 = 2 余 25,25 对应 Y
2 % 26 = 0 余 2, 2 对应 B
试题C:数列求值
int main(){
int a,b,c,d;
a=1,b=1,c=1;
d=3;
for(int i=4;i<=20190324;i++){
d=a+b+c;
d%=10000;
a=b,b=c,c=d;
}
cout<<d<<endl;
return 0;
}
//求解得到:4659
试题D:数的分解
/*
用dfs没有做出来,以下为他人的代码
*/
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#define ll long long
using namespace std;
int ans=0;
int a[3]= {0};
int vis[2020]= {0};//标记
bool existtf(int n) {//判断是否含有2,4
while(n>0) {
if(n%10==2||n%10==4)
return false;
n=n/10;
}
return true;
}
void dfs(int n) {
if(n==3) {
if(a[0]+a[1]+a[2]==2019&&a[0]!=a[1]&&a[1]!=a[2]&&a[0]!=a[2])
ans++;
return;//只要n==3,就要return,不是满足和为2019才return
}
for(int i=1; i<=2019; i++) {
if(existtf(i)) {
a[n]=i;
vis[i]=1;
dfs(n+1);
vis[i]=0;
}
}
}
int main() {
dfs(0);
cout<<ans/6<<endl;//每种情况重复3!次 ,需要除以6
return 0;
}
试题E:迷宫
//看了别人的代码,用BFS求解
#include <iostream>
#include <string>
#include <queue>
using namespace std;
int maze[35][55];
int dir[][2] = { { 1, 0 }, { 0, -1 }, { 0, 1 }, { -1, 0 } };
char d[4] = { 'D', 'L', 'R', 'U' };
int cnt = 0x3f3f3f3f;
bool vis[35][55];
struct node{
int x;
int y;
string rode;
int step;
node(int xx, int yy, string ss, int tt)
{
x = xx;
y = yy;
rode = ss;
step = tt;
}
};
bool check(int x, int y){
if (x <= 30 && x >= 1 && y <= 50 && y >= 1){
return true;
}
return false;
}
void bfs(int x, int y, string s, int num){
queue<node> q;
q.push(node(x, y, s, num));
while (!q.empty()){
node now = q.front();
q.pop();
vis[now.x][now.y] = true;
if (now.x == 30 && now.y == 50){
if (now.step < cnt){
cnt = now.step;
cout << now.step << endl;
cout<< now.rode << endl;
vis[now.x][now.y] = false;
}
continue;
}
for (int i = 0; i < 4; i++){
int tx = now.x + dir[i][0];
int ty = now.y + dir[i][1];
if (maze[tx][ty] == 0 && !vis[tx][ty] && check(tx, ty)){
q.push(node(tx, ty, now.rode + d[i], now.step + 1));
}
}
}
}
int main(){
for (int i = 1; i <= 30; i++){
for (int j = 1; j <= 50; j++){
maze[i][j] = getchar()-'0';
}
getchar();
}
bfs(1, 1, "", 0);
return 0;
}
bool check(int x,int n){
while(x){
if(x%10==n){
return false;
}
x/=10;
}
return true;
}
int main(){
int x,sum=0;
cin>>x;
for(int i=1;i<=x;i++){
if(!check(i,2)||!check(i,0)||!check(i,1)||!check(i,9)){
sum+=i;
}
}
cout<<sum <<endl;
return 0;
}
试题G:完全二叉树的权值
/*
完全二叉树:下一层的元素个数是上一层元素个数的2倍
*/
#include<iostream>
#include<cmath>
using namespace std;
#define INF 0x3f3f3f3f
#define N 100005
int num[N]={0}; //用一维数组存储完全二叉树
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>num[i];
int ans,k=0,max=-INF;
for(int i=0;i<ceil(log(n+1)/log(2));i++)
{
int sum=0;
for(int j=0;j<pow(2,i-1);j++)
sum+=num[k++];
if(sum>max)
{
max=sum;
ans=i;
}
}
cout<<ans<<endl;
return 0;
}
试题H:等差数列
先将N个数进行快排,取最大最小值,然后计算最小差值(比如样例中的最小差值是2),
最后直接利用等差数列公式(Max - Min) / Subtract + 1(比如(20 - 2) / 2 + 1 = 10)
返回最短等差数列项数。
试题I:后缀表达式
试题J:灵魂传输