子2023

【问题描述】
小蓝在黑板上连续写下从 1 到 2023 之间所有的整数,得到了一个数字序列:
S = 12345678910111213 . . . 20222023。
小蓝想知道 S 中有多少种子序列恰好等于 2023?
提示,以下是 3 种满足条件的子序列(用中括号标识出的数字是子序列包含的数字):
1234567891011121314151617181920212223...
1234567891011121314151617181920212223...
1234567891011121314151617181920212223...
注意以下是不满足条件的子序列,虽然包含了 2、0、2、3 四个数字,但是顺序不对:
1234567891011121314151617181920212223...

1.dp写法

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
typedef long long LL;
typedef pair<int,int> PII;
string s;
LL dp[5];

int main()
{
 	IOS;
	
	for(int i=1;i <= 2023;i++)	s+=to_string(i);

	for(int i=0;i < s.size();i++)
	{
		if(s[i] == '2')
		{
			dp[1]++;
			dp[3]+=dp[2];
		}
		
		if(s[i] == '0') dp[2]+=dp[1];
		if(s[i] == '3') dp[4]+=dp[3];
	}
		
	cout<<dp[4];
	
 	return 0;
}

2.剪枝后暴力

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
typedef long long LL;
typedef pair<int,int> PII;
string s;
LL ans=0;
string op="2023";

void dfs(int u,int cnt)
{
	if(cnt == 4)
	{
		ans++;
		return ;
	}
	if(u >= s.size()) return ;
	
	if(op[cnt] == s[u]) dfs(u+1,cnt+1);
	dfs(u+1,cnt);
}

int main()
{
 	IOS;
	
	for(int i=1;i <= 2023;i++)
	{
		string t=to_string(i);
		for(int j=0;j < t.size();j++)
		{
			if(t[j] == '2' || t[j] == '0' || t[j] == '3')
			s+=t[j];	
		}	
	} 	
	
	dfs(0,0);
	
	cout<<ans<<endl;
	
 	return 0;
}

枚举四个位置,只有数字放到该放的位置,才能填下一个位置,也可以选择不填。

相关推荐
依然鸣几秒前
PTA团体程序设计天梯赛L2真题讲解L2-045-048
数据结构·c++·经验分享·学习·算法·pat考试·pat
有点。5 分钟前
C++深度优先搜索(二)
开发语言·c++·深度优先
丢掉幻想准备斗争6 分钟前
5.5树与二叉树的应用
算法
ZhouDevin31 分钟前
算法论文/模型微调2——仅骨干1%~3% 参数达到与全量微调相当的性能
算法
Sinosecu-OCR1 小时前
文通OCR技术深度解析:自研算法如何搞定复杂场景识别?
算法·ocr·ocr识别系统
CQU_JIAKE1 小时前
8.5【A】
数据结构·算法
ESBK20251 小时前
学术邀约|CMICA 2026 第二届计算方法、智能控制与航空航天国际会议
大数据·人工智能·算法·飞行器·智能控制·航空航天·计算
小小龙学IT1 小时前
Taskflow:用一张“任务图“玩转现代 C++ 并行编程开源项
c++·开源·github
无bug代码搬运工2 小时前
LeetCode 42 接雨水:双指针解法详解
算法·leetcode·职场和发展
wuminyu2 小时前
JUC包的AQS与JVM的ObjectMonitor机制对比分析
java·linux·c语言·jvm·c++