题目:给你两个字符串,求一个最短的串,使得这两个串是目标串的子串。
分析:DP,最大公共子序列。最长目标串的长度为两串和减去最大公共子序列;
最长目标串的数量就是所有长度相同的情况的数量加和(路径的加和);
状态f(i,j)为串str1的前i个字符和串str2的前j个字符的最大匹配数,则有转移方程:
f(i,j) = f(i-1,j-1) { str1[i-1] == str2[j-1] }
= max(f(i-1,j),f(i,j-1)) { str1[i-1] != str2[j-1] }
说明:有可能有空串,用gets读数据;数据最大是2^32使用无符号整数。
#include <iostream> #include <cstdlib> #include <cstring> #include <cstdio> using namespace std; char str1[32],str2[32]; unsigned int F[32][32]; unsigned int S[32][32]; int main() { int n; while ( scanf("%d",&n) != EOF ) { getchar(); for ( int t = 1 ; t <= n ; ++ t ) { gets(str1);gets(str2); int L1 = strlen(str1); int L2 = strlen(str2); for ( int i = 0 ; i <= L1 ; ++ i ) for ( int j = 0 ; j <= L2 ; ++ j ) F[i][j] = S[i][j] = 0; for ( int i = 0 ; i <= L1 ; ++ i ) S[i][0] = 1; for ( int i = 0 ; i <= L2 ; ++ i ) S[0][i] = 1; for ( int i = 1 ; i <= L1 ; ++ i ) for ( int j = 1 ; j <= L2 ; ++ j ) if ( str1[i-1] == str2[j-1] ) { F[i][j] = F[i-1][j-1]+1; S[i][j] = S[i-1][j-1]; }else if ( F[i-1][j] > F[i][j-1] ) { F[i][j] = F[i-1][j]; S[i][j] = S[i-1][j]; }else if ( F[i-1][j] < F[i][j-1] ) { F[i][j] = F[i][j-1]; S[i][j] = S[i][j-1]; }else { F[i][j] = F[i-1][j]; S[i][j] = S[i-1][j] + S[i][j-1]; } printf("Case #%d: %u %u\n",t,L1+L2-F[L1][L2],S[L1][L2]); } } return 0; }
测试数据:(注意最后几组含有空串)
100 URRXCSCCVWATCGWSMALTJ HS NNGMSFVFML NAPBKMIBSRUJJEMEE TFGNSTCD HDNWG XHHUVMJWKRPPTVQEXMTOIXQDFCV GKAINHBJMPQCCOKKF SIGCLITOPEEFRAFKEJAEP KKMFHMXM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BFONLOFW XVNECOLBLHONSQKQHSCH VQVVUKPXSHOSIO ALJCKCFJ FRJLWDDWVHGNEFKNSWRXMFTGRRSAWC BMDKNEHXNUOFBUBSVKQ ODJOTMFKAKPBJIRHI UOUFSEIJSSTNJFVVFWLRKIKICOD NKLNVNDLPQAOLB LRNQHWN ODPIRJQMXRKXUVC GAUAQUAKIVNSNSWAMMUOU TRJGDAAR TCHBUOQRJVXMDHOXDSFE FHWGKQDIBJQMQJSIHEJVHNW GCXLVOTIBFC JVOQLTEDXET TCFDJF WCVXGFTBTOMOVVSWTJEKGNOBDSM FNMRDGXGTKTHKGCGCNUDF EWXTBVQSFQSTMIMBQDBGDPASAQVK EBUEVQQELAARODWSLUCLVMXCC TFFRMFQRROBJOWQIAFCL KWNQHCAOATKMJLMHXVQOQLV OSU KUAQSSHSKIVUEBKKOFR XUDS DGDR NWUNKJMBKPKBKNGSTLBDAXIHIISM COMFJHKGRCHKECGEPTMEVQTNDGC LSXJC XDUIWOML R VULMRACUNVESPSI VRVTRRAUBMVRSIDQSOFID BNXMVRVGWDCQFRFUMKGCCOPUNDU BHAAAABFNLWIIJPPGDEVJK BOVHDQPFIFITSJ CJSSEAINBBNJH EBSXKKGSTIFJBHOTDCEUQ UWUJVMG RWVUHLRPILGKUWBBRCGVRTLEHCE KSMBBOMUCWEIUAMBQUPCKJMJPL CGEFFILRJBTCGPNNQVCTMFGVDQERN DQDEDFTBBLUVVQWORKHISOOIH STXRQMBBJ EAFLQPFRKBDWHKKXJ QWSVDSOUOQPKBTJIE GNSNGADPRQPKSCMWGXGOWKGIEQQL QKGMMBXMRFOS XHCEFUJFXAP
UVa 10723 - Cyborg Genes
时间: 2024-10-06 19:17:21