51nod-1732 51nod婚姻介绍所

题目来源: 原创
基准时间限制:1 秒 空间限制:131072 KB 分值: 40  难度:4级算法题
 收藏
 关注
51nod除了在做OJ之外,还开展了很多副业。婚姻介绍所就是其中之一。

对于一个客户,我们可以使用一个字符串来描述该客户的特质。

假设现在我们有两个客户A和B。

A的特质字符串为:abcdefg
B的特质字符串为:abcxyz

则A和B的匹配度f(A, B)为A和B的最长公共前缀的长度,即len('abc') = 3

由于最近51nod经费紧张,所以夹克大老爷设计了一种压缩算法以节约内存。

所有用户的特质字符串都被存储在了一个长为n的字符串S中。(n <= 1000)用户的特质使用一个整数p表示,表示该用户的特质字符串为S[p...n - 1]。

现给定字符串S,与q次查询<ai, bi>(ai, bi分别为合法的用户特质整数)。请输出q次查询分别对应的客户匹配度。




Input
现给定字符串长度n,与字符串S。接下来是整数q,代表接下来有q次查询。
下面q行有两个整数ai, bi。代表查询特质为ai与bi的用户的匹配度。

1 <= n <= 1000
1 <= q <= 10^6

输入数据全部合法。
Output
每一行输出一个用户匹配度整数。
Input示例
12
loveornolove
5
3 7
0 0
9 1
3 1
9 5
Output示例
0
12
3
0
0

题解:本来想暴力预处理看看T了几个样例的,结果竟然过了。。样例真水。本方法预处理出所有的情况结果,最坏情况O(n^3)。。。。

AC代码

#include <stdio.h>
#include <iostream>
#include <string>
#include <queue>
#include <map>
#include <vector>
#include <algorithm>
#include <string.h>
#include <cmath>
 
using namespace std;

const int maxn = 1111;
char a[1111];
int dp[maxn][maxn] = {0};

int get_ans(int l, int r, int n){
	for(int i = 0; i + r < n; i++)
		if(a[l + i] != a[r + i])
			return i;
	return n - r;
}

void solve(int n){
	for(int len = 0; len < n; len++){
		for(int i = 0; i + len < n; i++){
			dp[i][i + len] = get_ans(i, i + len, n);
		}
	}
}

int main(){
	int n, q, l, r;
	scanf("%d", &n);
	scanf("%s", a);
	solve(n);
	scanf("%d", &q);
	for(int i = 0; i < q; i++){
		scanf("%d%d", &l, &r);
		printf("%d\n", dp[min(l, r)][max(l, r)]);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_37064135/article/details/80010541