Gdfzoj Sub-sequences

Source: Internet
Author: User

Tag: Represents the stream's location end strlen condition out CPP

Test instructions

Give two strings, A, B, find the LCS of A, B, and then extract a sub-sequence of length LCS, q How many are also the sub-sequences?

Exercises

First, it is clear that LCS must be required.

Now consider the record,

Now consider the definition: the first routine is defined according to the answer, the definition state sum[i][j] denotes the first I characters in a string, how many sub-sequences of length dp[i][j] have appeared in B.

Now consider the transfer: if dp[i][j] = = Dp[i-1][j], then sum[i][j] + = Sum[i-1][j] Indicates that the I-character is not selected

Now consider the required I-character, then you need to find the position of the last character in string B that is equal to a[i], and if dp[i-1][pre-1] + 1 = = Dp[i][j],sum[i][j] + + sum[i-1][pre-1]

Code:

#include <cstdio> #include <iostream> #include <cstring> #include <algorithm>using namespace std;const int N = 1e3 + 7;const int mod = 1e9 + 7;char ch1[n], Ch2[n];int dp[n][n], sum[n][n], N, M, Pre[n];int main () {g ETS (CH1 + 1), gets (CH2 + 1), n = strlen (ch1 + 1), M = strlen (CH2 + 1), for (int i = 0; I <= N; ++i) sum[i][0] = 1;for ( int j = 0; J <= M;  ++J) Sum[0][j] = 1;for (int i = 1; I <= n; ++i) {for (int j = 1; j <= m; ++j) {Dp[i][j] = max (Dp[i-1][j], dp[i][j -1]); if (ch1[i] = = Ch2[j]) dp[i][j] = max (Dp[i][j], dp[i-1][j-1] + 1);}} for (int j = 1; j <= m; ++j) {pre[ch2[j]] = j;for (int i = 1; I <= n; ++i) {if (dp[i-1][j] = = Dp[i][j]) sum[i][j] = (Sum[i][j] + sum[i-1][j])% mod;if (Pre[ch1[i]] && dp[i-1][pre[ch1[i]]-1] + 1 = = Dp[i][j]) {sum[i][j] = (sum I [j] + Sum[i-1][pre[ch1[i]]-1])% MoD;}} cout << sum[n][m] << endl;return 0;}

  

Summarize:

The basic condition of this problem is on the basis of LCS, first DP out all the conditions of the LCS, and then based on the basis of the DP to take the calculation scheme number.

Gdfzoj Sub-sequences

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.