51nod1732 51nod婚姻介绍所(DP)

本文介绍了一种使用动态规划解决51NOD平台上的题目1732的方法。通过预处理字符串的自匹配情况,实现了高效求解最长相同子串长度的功能,并附带了完整的AC代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1732

思路:简单的dp,预处理字符串的自匹配的就好,if str[i]==str[j] 有 dp[i][j] = 1+dp[i+1][j+1],用输入输出挂加速读入写出

AC代码:

#include<stdio.h>
#include<math.h>
#include<string.h>
const int MAXN = 1e3 + 5;
const int MOD = 1e9 + 7;
typedef long long LL;
const double PI = acos(-1.0);
const double E = exp(1.0);
using namespace std;

inline void readInt(int &x) {
	char c;
	x = 0;
	while ((c = getchar()) < '0' || c > '9');
	while (c >= '0'&&c <= '9') {
		x = x * 10 + c - '0';
		c = getchar();
	}
}
int dp[MAXN][MAXN], buf[10];
inline void writeInt(int i) {
	int p = 0;
	if (i == 0)p++;
	memset(buf, 0, sizeof(buf));
	if (i == 0)p++;
	else {
		while (i) {
			buf[p++] = i % 10;
			i /= 10;
		}
	}
	for (int j = p - 1; j >= 0; j--)putchar('0' + buf[j]);
}
int main() {
	int n, q;
	char str[MAXN];
	scanf("%d", &n);
	scanf("%s", str);
	int len = strlen(str);
	for (int i = len - 1; i >= 0; i--) {
		for (int j = i; j >= 0; j--) {
			if (i == len - 1 || j == len - 1) {
				dp[i][j] = (str[i] == str[j]);
			}
			else {
				if (str[i] == str[j]) {
					dp[i][j] = dp[i + 1][j + 1] + 1;
				}
			}
		}
	}
	scanf("%d", &q);
	while (q--) {
		int a, b;
		readInt(a);
		readInt(b);
		if (a < b) {
			a = a + b;
			b = a - b;
			a = a - b;
		}
		printf("%d\n", dp[a][b]);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值