跳到正文

题解

题解:P12377 [蓝桥杯 2023 省 Python B] 2023

Holy_Cabbage约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟
题目
P12377

版本

  1. v1当前

纯纯的暴力做法,众所不周知,暴力是不需要考虑时间复杂度的,所以就会有一种神奇的暴力做法。

由于数字都是八位数,就把它的每一个数位都问候一遍,由此可以做出一个 check 函数:

check 函数的思路: 用 x_1 到 x_8 来记录我要判断的数的每个数位是多少,再用字符串把我的数字改为字符形式,再用 string 专属函数 find 来分别找 22、00、22、33,若都有,返回 00,否则返回 11。

C++

C++
int check(int x){
	int x_1,x_2,x_3,x_4,x_5,x_6,x_7,x_8;
	x_8=x%10;
	x_7=x/100%10;
	x_6=x/1000%10;
	x_5=x/10000%10;
	x_4=x/100000%10;
	x_3=x/1000000%10;
	x_2=x/10000000%10;
	x_1=x/100000000%10;
	string s;
	s=x_1+'0',s+=x_2+'0',
	s+=x_3+'0',s+=x_4+'0',
	s+=x_5+'0',s+=x_6+'0',
	s+=x_7+'0',s+=x_8+'0';
	for(int i=0;i<8;i++){
		if(s.find('2')!=s.npos) i=s.find('2');
		else{return 1;}
		if(s.find('0')!=s.npos) i=s.find('0');
		else{return 1;}
		if(s.find('2')!=s.npos) i=s.find('2');
		else{return 1;}
		if(s.find('3')!=s.npos) i=s.find('3');
		else{return 1;}
	}return 0;
}

Python

Python
def check(x):
    s = f"{x:08d}"
    # 按顺序检查子序列
    try:
        pos = s.index('2')
        pos = s.index('0', pos+1)
        pos = s.index('2', pos+1)
        pos = s.index('3', pos+1)
        return 0
    except ValueError:
        return 1

再加一个循环问候 1234567812345678 至 9876543298765432 全家,就出现一个总代码。

Code:

C++

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod=1e9+7;
int check(int x){
	int x_1,x_2,x_3,x_4,x_5,x_6,x_7,x_8;
	x_8=x%10;
	x_7=x/100%10;
	x_6=x/1000%10;
	x_5=x/10000%10;
	x_4=x/100000%10;
	x_3=x/1000000%10;
	x_2=x/10000000%10;
	x_1=x/100000000%10;
	string s;
	s=x_1+'0',s+=x_2+'0',
	s+=x_3+'0',s+=x_4+'0',
	s+=x_5+'0',s+=x_6+'0',
	s+=x_7+'0',s+=x_8+'0';
	for(int i=0;i<8;i++){
		if(s.find('2')!=s.npos) i=s.find('2');
		else{return 1;}
		if(s.find('0')!=s.npos) i=s.find('0');
		else{return 1;}
		if(s.find('2')!=s.npos) i=s.find('2');
		else{return 1;}
		if(s.find('3')!=s.npos) i=s.find('3');
		else{return 1;}
	}return 0;
}signed main(){
	ios::sync_with_stdio(0),
	cin.tie(0),cout.tie(0);
	int ans=0;
	for(int i=12345678;i<=98765432;i++)
		if(check(i)) ans++;
	cout<<ans;
	return 0;
}

Python

Python
def check(x):
    # 将数字格式化为8位字符串(自动补前导零)
    s = f"{x:08d}"

    # 顺序查找子序列 2->0->2->3
    try:
        pos = s.index('2')         # 找第一个2
        pos = s.index('0', pos+1)  # 在第一个2之后找0
        pos = s.index('2', pos+1) # 在0之后找第二个2
        pos = s.index('3', pos+1)  # 在第二个2之后找3
        return 0  # 找到完整序列
    except ValueError:
        return 1   # 未找到

def main():
    count = 0
    # 遍历所有8位数(包含端点)
    for num in range(12_345_678, 98_765_432 + 1):
        if check(num):
            count += 1
    print(count)

if __name__ == "__main__":
    main()

时间非常快(不建议 直接 使用),只需几个小时反正得出答案是 8595903085959030。

再来个答案输出。

Code:

C++

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod=1e9+7;

signed main(){
	ios::sync_with_stdio(0),
	cin.tie(0),cout.tie(0);
	cout<<"85959030";
	return 0;
}

Python

Python
print("85959030")
原文