fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5. #define print(a) for(auto x : a) cout << x << " "; cout << endl
  6.  
  7.  
  8. const int M = 1000000007;
  9. const int N = 3e5+9;
  10. const int INF = 2e9+1;
  11. const int LINF = 2000000000000000001;
  12.  
  13. inline int power(int a, int b, int mod=M) {
  14. int x = 1;
  15. a %= mod;
  16. while (b) {
  17. if (b & 1) x = (x * a) % mod;
  18. a = (a * a) % mod;
  19. b >>= 1;
  20. }
  21. return x;
  22. }
  23.  
  24.  
  25. //_ ***************************** START Below *******************************
  26.  
  27.  
  28.  
  29.  
  30. string a;
  31. string b;
  32.  
  33. int consistency(int n, int m){
  34.  
  35. if(n<m) return -1;
  36.  
  37. vector<int> prefix(26, 0);
  38. vector<int> sufix(26, 0);
  39. for(int i=0; i<n; i++){
  40. prefix[a[i]-'a']++;
  41. sufix[a[i]-'a']++;
  42. }
  43.  
  44. //* fwd
  45. int count = 0;
  46. int i = 0, j = 0;
  47.  
  48. int s1 = n+1;
  49.  
  50. while(i<n && j<m){
  51.  
  52. if(sufix[b[j]-'a'] > 0){
  53. while(i<n && a[i] != b[j]){
  54. sufix[a[i]-'a']--;
  55. i++;
  56. }
  57. }
  58. else{
  59. count++;
  60. }
  61.  
  62. if(i==n) break;
  63.  
  64. s1 = min(s1, i);
  65. sufix[a[i]-'a']--;
  66. i++;
  67. j++;
  68. }
  69.  
  70. if(count > 1 || j!=m ) s1 = -1;
  71. if(count == 0) s1 = 0;
  72.  
  73.  
  74.  
  75. //* bkwd
  76. count = 0;
  77. i = n-1, j = m-1;
  78.  
  79. int s2 = n+1;
  80.  
  81. while(i>=0 && j>=0){
  82.  
  83. if(prefix[b[j]-'a'] > 0){
  84. while(i>=0 && a[i] != b[j]){
  85. prefix[a[i]-'a']--;
  86. i--;
  87. }
  88. }
  89. else{
  90. count++;
  91. }
  92.  
  93. if(i==-1) break;
  94.  
  95. s2 = min(s2, i);
  96. prefix[a[i]-'a']--;
  97. i--;
  98. j--;
  99. }
  100.  
  101. if(count > 1 || j!=-1) s2 = -1;
  102. if(count == 0) s2 = 0;
  103.  
  104.  
  105. if(s1 == -1 && s2 == -1) return -1;
  106. if(s1 == -1) return s2+1;
  107. if(s2 == -1) return s1+1;
  108. return min(s1, s2)+1;
  109.  
  110. }
  111.  
  112.  
  113.  
  114.  
  115.  
  116.  
  117.  
  118.  
  119.  
  120.  
  121.  
  122.  
  123.  
  124. // string a;
  125. // string b;
  126.  
  127. int practice(int n, int m){
  128.  
  129.  
  130. return 0;
  131. }
  132.  
  133.  
  134.  
  135.  
  136.  
  137. void solve() {
  138.  
  139. cin >> a >> b;
  140. int n = a.size();
  141. int m = b.size();
  142.  
  143. cout << consistency(n, m) << endl;
  144.  
  145.  
  146. }
  147.  
  148.  
  149.  
  150.  
  151.  
  152. int32_t main() {
  153. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  154.  
  155. int t = 1;
  156. cin >> t;
  157. while (t--) {
  158. solve();
  159. }
  160.  
  161. return 0;
  162. }
Success #stdin #stdout 0s 5316KB
stdin
2
dbeacq
abe
xbabc
abc
daabe
abe
daacp
abe
daace
abe
stdout
1
1