蓝桥杯 省赛 接龙数列 DP 记忆化搜索

⭐ 接龙数列
蓝桥杯 省赛 接龙数列 DP 记忆化搜索_第1张图片

输入样例
5
11 121 22 12 2023
输出样例

1

⭐ 动态规划(过50%)

import java.io.*;

public class Main
{
	static int N = 100010;
	static int[] l = new int[N];
	static int[] r = new int[N];
	static int[] f = new int[N];

	static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

	public static void main(String[] args) throws IOException
	{
		int n = Integer.parseInt(in.readLine());
		String[] ss = in.readLine().split(" ");
		String s;
		int left, right;

		for (int i = 0; i < n; i++)
		{
			s = ss[i];
			left = s.charAt(0);
			right = s.charAt(s.length() - 1);
			l[i] = left;
			r[i] = right;
		}
		int ans = 0;
		for (int i = 0; i < n; i++)
		{
			f[i] = 1;
			for (int j = 0; j < i; j++)
				if (l[i] == r[j])
					f[i] = Math.max(f[i], f[j] + 1);

			ans = Math.max(ans, f[i]);
		}

		System.out.println(n - ans);
	}
}

⭐ 时间优化

① 只关心以 l[i] 结尾的最大接龙数,开一个数组记录以 i 结尾的最大接龙数即可减少一重循环
import java.io.*;

public class Main
{
	static int N = 100010;
	static int[] l = new int[N];
	static int[] r = new int[N];
	static int[] f = new int[N];
	static int[] g = new int[11];//记录以 i 结尾的最大接龙数

	static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

	public static void main(String[] args) throws IOException
	{
		int n = Integer.parseInt(in.readLine());
		String[] ss = in.readLine().split(" ");
		String s;
		int left, right;

		for (int i = 0; i < n; i++)
		{
			s = ss[i];
			left = s.charAt(0)- '0';
			right = s.charAt(s.length() - 1) - '0';
			l[i] = left;
			r[i] = right;
		}
		int ans = 0;
		for (int i = 0; i < n; i++)
		{
			f[i] = 1;
			f[i] = Math.max(f[i], g[l[i]] + 1);
			g[r[i]] = Math.max(g[r[i]], f[i]);

			ans = Math.max(ans, f[i]);
		}

		System.out.println(n - ans);
	}
}

⭐ 空间优化

① f[i] 并不依赖前边的项,一个变量 f 即可
② left right 也只是用一次,而且输入和DP的循环一致,直接边输入边处理即可,开两个变量 left right
import java.io.*;

public class Main
{
	static int N = 100010;
	static int[] g = new int[11];//记录以 i 结尾的最大接龙数

	static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

	public static void main(String[] args) throws IOException
	{
		int n = Integer.parseInt(in.readLine());
		String[] ss = in.readLine().split(" ");
		String s;
		int left, right;
		int ans = 0;

		for (int i = 0; i < n; i++)
		{
			s = ss[i];
			left = s.charAt(0)- '0';
			right = s.charAt(s.length() - 1) - '0';
            int f = 1;
			f = Math.max(f, g[left] + 1);
			g[right] = Math.max(g[right], f);

			ans = Math.max(ans, f);
		}

		System.out.println(n - ans);
	}
}

你可能感兴趣的:(算法题解,蓝桥杯,算法,职场和发展)