寻找最长公共后缀
注意: 边界情况: 两条链没有交集, 其中一条链是另一条链的子链
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <stack> #include <queue> #include <map> #include <set> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <climits> using namespace std;
#ifdef _DEBUG template <class T> void ERR(T x, string name) { cout << "[DEBUG]{" << name << "} = " << x << endl; } # define debug(x) ERR(x, #x) #else # define debug(...) 0 #endif
map<string, pair<char, string>> M;
int main() { #ifdef _DEBUG freopen(__FILE__ ".txt", "r", stdin); #endif
string w1, w2; int n; cin >> w1 >> w2 >> n;
for (int i = 0; i < n; i++) { string a, b; char c; cin >> a >> c >> b; M[a] = make_pair(c, b); }
stack<string> s1, s2; debug("s1"); for (string addr = w1; addr != "-1"; addr = M[addr].second) { s1.push(addr); debug(addr); } debug("s2"); for (string addr = w2; addr != "-1"; addr = M[addr].second) { s2.push(addr); debug(addr); }
string top = "-1"; while (s1.size() && s2.size() && s1.top() == s2.top()) { top = s1.top(); debug(top); s1.pop(); s2.pop(); }
cout << top << endl;
return 0; }
|