[蓝桥杯 2023 省 A] 更小的数【两种简单方法实现】

  • 题意概要:
    • 从输入的数num中选择一段连续子串(未限定长度,根据对题意的理解,2<=str_len<=n,n为输入字符串长度),
      反转一次放入原位置,满足num_new<num;
    • 输入:
      长度为n的字符串(十进制数num)。字符串元素为0-9。
    • 输出:
      满足题意条件的子串选择方案个数。
      *:允许前导0的存在。
// 伪代码:
for(int i=0;i<=n-1;i++){//子串的第一个元素位置 
			//子串长度[2,n]
		for(int j=i+1;j<=n-1;j++){
		//当前子串长度:i~j
		if(num_i_to_j<num) cnt++; 
		}
	}//时间复杂度:o(10^7)
//方法1:简单模拟
#include<iostream>
using namespace std;
#include<cstdio> 
#include<cstring> 
const int maxn=5010;
int cmp(char x[],int len){//str[]设置为全局变量就不用传入子串了,而是直接传入str[]子串的下标即可。 
	//比较子串反转前后大小关系x[0]~x[len-1]
	for(int i=0;i<=len/2-1;i++){//这里直接比较字符的大小即可,无需化成字符对应是数字再比较大小。 
		if(x[i]==x[len-i-1]) continue;
		else if(x[i]>x[len-i-1]) return 1;
		else if(x[i]<x[len-i-1]) return 0;
	}
	return 0;
}
int main()
{
    char str[maxn],substr[maxn];//输入字符串与子串
    scanf("%s",str);
    int cnt=0;//满足条件的子串个数 
    int len=strlen(str);
    int sub_idx=0;//子串下标
    for(int i=0;i<=len-2;i++){//子串起始位置 
    	sub_idx=0;
    	substr[sub_idx]=str[i];
    	sub_idx++;
    	for(int j=i+1;j<=len-1;j++){//子串长度
			substr[sub_idx]=str[j];
    		int flag=cmp(substr,j-i+1); 
    		if(flag) cnt++;
			sub_idx++;
		}
	}
	cout<<cnt;
    return 0;
}
//方法2:使用string容器的简单模拟【代码更精简易懂,推荐使用】
#include<bits/stdc++.h>
using namespace std;
string s;
int judge(int l,int r){
	//比较传入的子串反转后是否变小
	while(l<r){
		if(s[l]==s[r]){
			l++;
			r--;
			continue;
		}else if(s[l]<s[r]) return 0;
		else return 1;
	}
	return 0; 
}
int main(){
	cin>>s;
	int l=0,r=0;//l:指向当前子串左端,r:指向当前子串右端
	int len=s.length(); 
	int cnt=0;//满足条件的子串个数 
	for(int l=0;l<len-1;l++){
		for(int r=l+1;r<=len-1;r++){
			//当前子串范围为[l,r]
			if(judge(l,r)) cnt++; 
		}
	}
	cout<<cnt;
	return 0;
}
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值