Topic source: original
Baseline Time Limit: 1 second Space Limit: 131072 KB Score: 40
Difficulty: Level 4 Algorithm Questions
In addition to doing OJ, 51nod has also started a lot of side businesses. A marriage agency is one of them.
For a customer, we can use a string to describe the characteristics of the customer.
Suppose now we have two customers A and B.
A's trait string is: abcdefg
B's trait string is: abcxyz
Then the matching degree f(A, B) of A and B is the length of the longest common prefix of A and B, that is, len('abc') = 3
Due to the tight budget of 51nod recently, the Jacket Master designed a compression algorithm to save memory.
All user trait strings are stored in a string S of length n. (n <= 1000) The user's trait is represented by an integer p, indicating that the user's trait string is S[p...n - 1].
Now given a string S, query <ai, bi> q times (ai, bi are valid user trait integers respectively). Please output the customer matching degree corresponding to q queries.
Input
Now given string length n, and string S. Next is the integer q, which means that there are q queries next. The following line q has two integers ai, bi. Represents the matching degree of users whose query characteristics are ai and bi. 1 <= n <= 1000 1 <= q <= 10^6 All data entered is legal.
Output
Each line outputs a user matching degree integer.
Input example
12 loveornolove 5 3 7 0 0 9 1 3 1 9 5
Output example
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; }