Substrings-3 Input file: stdin Output file: stdout Time limit: 2 sec Memory limit: 256…
- User
Substrings-3 Input file: stdin
Output file: stdout
Time limit: 2 sec
Memory limit: 256 mb
You are given strings of lowercase Latin letters. Find their longest common substring.
Input The first line contains a single integer ().
Next lines contain given (each string is at least and at most characters long), one per line.
- Assistant
- User
write in competitive style with bits and no comments
- Assistant
Certainly! Here’s a competitive programming-style implementation of the longest common substring solution without comments:
#include <iostream> #include <vector> #include <string> #include <unordered_set> #include <algorithm> using namespace std; bool hasCommonSubstring(const vector<string>& strings, int length, string& commonSubstring) { unordered_set<string> substrings; for (int i = 0; i <= strings[0].size() - length; i++) { substrings.insert(strings[0].substr(i, length)); } for (int i = 1; i < strings.size(); i++) { bool found = false; for (int j = 0; j <= strings[i].size() - length; j++) { string sub = strings[i].substr(j, length); if (substrings.count(sub)) { found = true; commonSubstring = sub; break; } } if (!found) return false; } return true; } string longestCommonSubstring(const vector<string>& strings) { int low = 1, high = min_element(strings.begin(), strings.end(), [](const string& a, const string& b) { return a.size() < b.size(); })->size(); string result = ""; while (low <= high) { int mid = low + (high - low) / 2; string commonSubstring; if (hasCommonSubstring(strings, mid, commonSubstring)) { result = commonSubstring; low = mid + 1; } else { high = mid - 1; } } return result; } int main() { int k; cin >> k; vector<string> strings(k); cin.ignore(); for (int i = 0; i < k; i++) { getline(cin, strings[i]); } cout << longestCommonSubstring(strings) << endl; return 0; } - User
Substrings-3 Input file: stdin
Output file: stdout
Time limit: 2 sec
Memory limit: 256 mb
You are given strings of lowercase Latin letters. Find their longest common substring.
Input The first line contains a single integer ().
- Assistant