蓝桥杯真题讲解:接龙序列

本文介绍了蓝桥杯竞赛中的接龙序列问题,提供了暴力代码(深度优先搜索)实现以及优化后的线性动态规划解决方案,展示了从暴力求解到高效算法的转变。
摘要由CSDN通过智能技术生成

蓝桥杯真题讲解:接龙序列

一、视频讲解

蓝桥杯真题讲解:接龙序列
在这里插入图片描述

二、暴力代码

// 暴力代码:DFS(2^n)
#include<bits/stdc++.h>
#define endl '\n'
#define deb(x) cout << #x << " = " << x << '\n';
#define INF 0x3f3f3f3f
using namespace std;
const int N = 1e5 + 10;
int a[N];
int n, ans;

int get_first(int x)//获取数字的最高位
{
	int res = 0;
	while(x)
	{
		res = x % 10;
		x /= 10;
	}
	return res;
}

int get_final(int x)//获取数字的最后一位
{
	return x % 10;
}


//u表示当前考虑到了第几位。
//last表示,方案中已经选了的最后一个数字是多少
//cnt表示,方案中一共有多少个数字
void dfs(int u, int cnt, int last)
{
	if(u >= n)
	{
		ans = max(ans, cnt);
		return;
	}

	if(n - u + cnt <= ans)
	{
		return;
	}

	//第u位数选,如果选这个数字
	//就必须和前面最后一个数字构成接龙序列。
	if(last == -1 || get_final(last) == get_first(a[u]))
		dfs(u + 1, cnt + 1, a[u]);

	//第u个数不选
	dfs(u + 1, cnt, last);
}

void solve()
{
	cin >> n;
	for(int i = 0; i < n; i ++)
		cin >> a[i];

	dfs(0, 0, -1);
	cout << n - ans << endl;
}

signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int t;
	t = 1;
	//cin >> t;
	while(t--)
	solve();
}

三、正解代码

//接龙序列:线性DP
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
const int N = 1e5 + 10;

int f[N][15];

int get_first(int x)
{
	int res = 0;
	while(x)
	{
		res = x % 10;
		x /= 10;
	}
	return res;
}

int get_final(int x)
{
	return x % 10;
}

void solve()
{
	memset(f, INF, sizeof f);
	int n;
	cin >> n;
	vector<int>a(n + 1);
	
	for(int i = 1; i <= n; i ++)
		cin >> a[i];
	
	for(int i = 0; i < 10; i ++)
		f[0][i] = 0;

	for(int i = 1; i <= n; i ++)
	{
		//删除第i个数字
		for(int j = 0; j < 10; j ++)
			f[i][j] = f[i - 1][j] + 1;

		//保留第i个数字
		int final = get_final(a[i]);
		int first = get_first(a[i]);

		f[i][final] = min(f[i - 1][first], f[i][final]);
	}

	int ans = INF;
	for(int i = 0; i < 10; i ++)
		ans = min(ans, f[n][i]);

	cout << ans << endl;
}

signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	int t = 1;
	// cin >> t;
	while(t--)
	solve();
}

  • 32
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值