int longest_common_substr(char str1[], char str2[], int pos1, int pos2, int len1, int len2, int table[][MAX]) { if(pos1>=len1 || pos2>=len2) { return 0; } if(table[pos1][pos2 ] != -1) { return table[pos1][pos2]; } if(str1[pos1] == str2[pos2]) { table[pos1][pos2] = 1 + longest_common_substr(str1, str2, pos1+1, pos2+1, len1, len2, table); } else { table[pos1][pos2] = 0; longest_common_substr(str1, str2, pos1+1, pos2, len1, len2, table); longest_common_substr(str1, str2, pos1, pos2+1, len1, len2, table); } // calculate the max for(int i = 0; i<MAX; i++) { for(int j = 0; j<MAX; j++) { if(table[i][j] > longest) { longest = table[i][j]; } } } return longest; }
void main() { char str1[] = "iavinashrameshpatil"; char str2[] = "helloavinashrpatlmdncv"; int len1 = strlen(str1); int len2 = strlen(str2); int table[MAX][MAX]; for(int i = 0; i<MAX; i++) { for(int j = 0; j<MAX; j++) { table[i][j] =-1; } } printf("longest common subseq length is %d", longest_common_subseq(str1, str2, 0, 0, len1, len2, table)); for(int i = 0; i<MAX; i++) { for(int j = 0; j<MAX; j++) { table[i][j] =-1; } } printf("longest common substr length is %d", longest_common_substr(str1, str2, 0, 0, len1, len2, table)); }
void handleIO() { #ifdef FILE_IO std::string problem = "11557"; std::ifstream inFile(problem + "_in.txt"); std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf std::cin.rdbuf(inFile.rdbuf()); //redirect std::cin to inFile! std::ofstream outFile(problem + "_out.txt"); std::streambuf *coutbuf = std::cout.rdbuf(); std::cout.rdbuf(outFile.rdbuf()); #endif int n = 0; while (std::cin >> n) { std::vector<code_fragment> fragments(n); std::vector<std::string> file_names(n); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // n file names and n code fragments for (int i = 0; i < n; i++) { // input file name std::getline(std::cin, file_names[i]); // std::cout << "got file name " << file_names[i] << std::endl; // input code fragment std::string line; while (std::getline(std::cin, line) && line != "***END***") { std::string tline = reduce(line); if (tline.length() > 0) fragments[i].push_back(tline); } } // input repo code fragment code_fragment repo_fragment; std::string line; while (std::getline(std::cin, line) && line != "***END***") { std::string tline = reduce(line); if (tline.length() > 0) repo_fragment.push_back(tline); } int maxLen = 0; std::vector<int> lc_match(n); // compare repo code fragment with each code fragment for (int i = 0; i < n; i++) { lc_match[i] = longest_common_substr(fragments[i], repo_fragment); maxLen = std::max(maxLen, lc_match[i]); } if (maxLen == 0) std::cout <<0<< std::endl; else { std::cout << maxLen; for (int i = 0; i < n; i++) { auto len_match = lc_match[i]; if (len_match == maxLen) std::cout << " " << file_names[i]; } std::cout << std::endl; } } #ifdef FILE_IO std::cin.rdbuf(cinbuf); inFile.close(); std::cout.rdbuf(coutbuf); outFile.close(); #endif }