1. 程式人生 > 實用技巧 >CF1360F Spy-string(暴力)

CF1360F Spy-string(暴力)

傳送門

思路:如果給定的字串中,存在一個下標出現了不同的字元,說明這個地方一定只能存在兩種字元,如果某個字元在當前位置被改變,則該字串之後的字元都要相同,然後我們就可以按照這個想法組成一個字串,然後讓這個字串去和所有字串比較,相同位置最多出現一個不同的字元("字串長度為1"和"所有字串都相同"需要特殊判斷下)。

  1 #include<iostream>
  2 #include<string>
  3 #include<vector>
  4 #include<cstdio>
  5 
  6 #define ll long long
  7
#define pb push_back 8 9 using namespace std; 10 11 const int N = 1e5 + 10; 12 vector<string > vs; 13 int n, m; 14 15 bool proess(string& s, int x, int pos, char c) 16 { 17 //cout << "proess----" << endl; 18 string str = s; 19 //cout << str << endl;
20 str += c; 21 for(int i = x + 1; i < m; ++i) str += vs[pos][i]; 22 //cout << "(str = " << str << ")" << endl; 23 bool ok = 1; 24 for(int i = 0; i < n; ++i){ 25 int dif = 0; 26 for(int j = 0; j < m; ++j){ 27 if(str[j] != vs[i][j]) dif++;
28 } 29 if(dif > 1) ok = 0; 30 } 31 32 return ok; 33 } 34 35 string fun(int x) 36 { 37 38 string str; 39 for(int i = 0; i < x; ++i) str += vs[0][i]; 40 for(int i = 0; i < n; ++i){ 41 char ch = vs[i][x]; 42 43 for(int j = 0; j < n; ++j){ 44 if(vs[j][x] != ch){ 45 if(proess(str, x, j, ch)){ 46 str += ch; 47 for(int k = x + 1; k < m; ++k) str += vs[j][k]; 48 return str; 49 } 50 } 51 } 52 } 53 54 return "false"; 55 } 56 57 void solve() 58 { 59 int T; 60 cin >> T; 61 while(T--){ 62 vs.clear(); 63 string str; 64 cin >> n >> m; 65 66 int len = 0; 67 for(int i = 1; i <= n; ++i){ 68 cin >> str; 69 vs.pb(str); 70 } 71 72 if(m == 1){ 73 cout << "a" << endl; 74 continue; 75 } 76 77 for(int i = 0; i < m; ++i){ 78 char ch = vs[0][i]; 79 int same = 0; 80 for(int j = 0; j < n; ++j){ 81 if(ch == vs[j][i]) same++; 82 } 83 if(same != n){ 84 //cout << "inx = " << i << endl; 85 string res = fun(i); 86 cout << (res == "false" ? "-1" : res) << endl; 87 break; 88 }else len++; 89 } 90 91 if(len == m) cout << vs[0] << endl; 92 } 93 } 94 95 int main() { 96 97 ios::sync_with_stdio(false); 98 cin.tie(0); 99 cout.tie(0); 100 solve(); 101 //cout << "ok" << endl; 102 return 0; 103 }