首页 > 代码库 > UVA 10100 Longest Match
UVA 10100 Longest Match
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=13&page=show_problem&problem=1041
LCS类型的题,不过并不是找common character,而是common word.就先把string处理成a list of word,然后再用LCS算法求common word。
代码如下:
1 #include <iostream> 2 #include <math.h> 3 #include <stdio.h> 4 #include <cstdio> 5 #include <algorithm> 6 #include <string.h> 7 #include <cstring> 8 #include <queue> 9 #include <vector> 10 #include <functional> 11 #include <cmath> 12 #define SCF(a) scanf("%d", &a) 13 #define IN(a) cin>>a 14 #define FOR(i, a, b) for(int i=a;i<b;i++) 15 typedef long long Int; 16 using namespace std; 17 18 int main() 19 { 20 char str1[1005], str2[1005]; 21 vector<string> v1, v2; 22 int testCase = 1; 23 int len1 = 0, len2 = 0; 24 while (cin.getline(str1, 1005)) 25 { 26 cin.getline(str2, 1005); 27 int cnum = 0; 28 char word[25]; 29 string wd; 30 len1 = 0; 31 len2 = 0; 32 for (int i = 0; str1[i] != ‘\0‘; i++) 33 { 34 len1++; 35 if ((str1[i] >= ‘a‘ && str1[i] <= ‘z‘) || (str1[i] >= ‘A‘ && str1[i] >= ‘Z‘) || (str1[i] >= ‘0‘ && str1[i] <= ‘9‘)) 36 { 37 word[cnum++] = str1[i]; 38 } 39 else 40 { 41 if (cnum > 0) 42 { 43 word[cnum++] = ‘\0‘; 44 wd = string(word); 45 v1.push_back(wd); 46 } 47 cnum = 0; 48 } 49 } 50 if (cnum > 0) 51 { 52 word[cnum++] = ‘\0‘; 53 wd = string(word); 54 v1.push_back(wd); 55 } 56 cnum = 0; 57 for (int i = 0; str2[i] != ‘\0‘; i++) 58 { 59 len2++; 60 if ((str2[i] >= ‘a‘ && str2[i] <= ‘z‘) || (str2[i] >= ‘A‘ && str2[i] >= ‘Z‘) || (str2[i] >= ‘0‘ && str2[i] <= ‘9‘)) 61 { 62 word[cnum++] = str2[i]; 63 } 64 else 65 { 66 if (cnum > 0) 67 { 68 word[cnum++] = ‘\0‘; 69 wd = string(word); 70 v2.push_back(wd); 71 } 72 cnum = 0; 73 } 74 } 75 if (cnum > 0) 76 { 77 word[cnum++] = ‘\0‘; 78 wd = string(word); 79 v2.push_back(wd); 80 } 81 82 int **match = new int*[v1.size() + 1]; 83 FOR(i, 0, v1.size() + 1) 84 match[i] = new int[v2.size() + 1]; 85 86 FOR(i, 0, v1.size() + 1) 87 match[i][0] = 0; 88 FOR(i, 0, v2.size() + 1) 89 match[0][i] = 0; 90 91 FOR(i, 1, v1.size() + 1) 92 { 93 FOR(j, 1, v2.size() + 1) 94 { 95 if (v1[i - 1] == v2[j - 1]) 96 match[i][j] = match[i - 1][j - 1] + 1; 97 else 98 match[i][j] = max(match[i - 1][j], match[i][j - 1]); 99 } 100 } 101 if(len1==0 || len2==0) 102 printf("%2d. Blank!\n", testCase++); 103 else 104 printf("%2d. Length of longest match: %d\n", testCase++, match[v1.size()][v2.size()]); 105 106 while (!v1.empty()) 107 v1.pop_back(); 108 while (!v2.empty()) 109 v2.pop_back(); 110 111 FOR(i, 0, v1.size() + 1) 112 delete[] match[i]; 113 delete[] match; 114 115 } 116 return 0; 117 }
UVA 10100 Longest Match
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。