問題C.文字列ゲーム(dp)

問題C.文字列ゲーム

入力ファイル:標準入力
出力ファイル:標準出力
制限時間:1秒
メモリ制限:256メガバイト

クレアとボブはゲームをします。クレアは小文字の文字列を作成します。ボブは、
お気に入りのサブシーケンスの1つをゲームのキーワードとして選択して、パズルを設定します。しかし、ボブはとても愚かだったので
、いくつかの文字を間違えるかもしれません。
ここで、Clairは、Bobの文字列がClairの文字列のサブシーケンスであるかどうか、および
Bobの文字列がClairの文字列のサブシーケンスとして何回表示されるかを知りたいと考えています。答えは非常に大きい可能性があるため、
109 + 7を法として答え出力する必要があります。
入力
最初の行はクレアの文字列(長さが5000以下)で、2番目の行はボブの文字列
(長さが1000以下)です。 )。
出力
ボブの文字列が
クレアの文字列のサブシーケンスとして表示される回数を表す単一の整数を含む1行を出力します。答えは109の+ 7モジュロべき
例を
標準入力、標準出力を
eeettt

eeettt
TE
9
0

質問:
メイン文字列の文字列とサブ文字列の文字列を指定して、メイン文字列内の部分文字列を一致させることができます。一致する部分文字列は、部分文字列文字と同じ順序である限り、連続する部分文字列である必要はありません。成功した試合としてカウントされます。
問題の解決策:
dp、再帰的に伝達方程式を書くだけ

ACコード:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cctype>
#include<iomanip>
#include<map>
#include<vector>
#include<list>
#include<deque>
#include<stack>
#include<queue>
#include<set>
#include<cctype>
#include<string>
#include<stdexcept>
#include<fstream>
#define mem(a,b) memset(a,b,sizeof(a))
#define dedebug() puts("what the fuck!")
#define debug(a) cout<<#a<<"="<<a<<endl;
#define speed {
    
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); };
#define ll long long
using namespace std;
const double PI = acos(-1.0);
const int maxn = 1e6 + 50;
const int INF = 0x3f3f3f3f;
const double esp_0 = 1e-6;
const int mod = 1e9 + 7;
ll gcd(ll x, ll y) {
    
    
	return y ? gcd(y, x % y) : x;
}
ll lcm(ll x, ll y) {
    
    
	return x * y / gcd(x, y);
}
ll extends_gcd(ll a, ll b, ll& x, ll& y) {
    
    
	if (b == 0) {
    
    
		x = 1;
		y = 0;
		return a;
	}
	ll gcdd = extends_gcd(b, a % b, x, y);
	ll temp = x;
	x = y;
	y = temp - (a / b) * y;
	return gcdd;
}
char str[5010];
char sub[1010];
int dp[1010][5010];
int main() {
    
    
	while (~scanf("%s%s", str + 1, sub + 1)) {
    
    
		mem(dp, 0);
		int lenstr = strlen(str + 1);
		int lensub = strlen(sub + 1);
		for (int i = 1; i <= lensub; ++i) {
    
    
			for (int j = 1; j <= lenstr; ++j) {
    
    
				if (sub[i] == str[j]) {
    
    
					if (i == 1) {
    
    
						dp[i][j] = (dp[i][j - 1] + 1) % mod;
					}
					else {
    
    
						dp[i][j] = (dp[i - 1][j - 1] + dp[i][j - 1]) % mod;
					}
				}
				else {
    
    
					dp[i][j] = dp[i][j - 1];
				}
			}
		}
		printf("%d\n", dp[lensub][lenstr]);
	}
	return 0;
}

おすすめ

転載: blog.csdn.net/qq_40924271/article/details/110006249