Advertisement
Guest User

Untitled

a guest
Sep 20th, 2014
798
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. using namespace std;
  5.  
  6. const int MOD = 1013;
  7. const int MAXQ = 10;
  8.  
  9. void solve(string spell, int code) {
  10.     // map<hash, number of strings with this hash>
  11.     map<int, long long> cnt;
  12.     cnt[0] = 1;
  13.  
  14.     // table used to reconstruct solution,
  15.     // prev[number of '?'][hash] = {char used, previous hash}
  16.     int prev[MAXQ][MOD][2] = {};
  17.  
  18.     int q = 0;  // running number of '?'
  19.     int k = 1;  // running power of 31
  20.     for (int i = spell.size()-1; i >= 0; i--) {
  21.         if (spell[i] != '?') {
  22.             // update hash by throwing away known chars
  23.             code -= k * spell[i] % MOD;
  24.             if (code < 0) {
  25.                 code += MOD;
  26.             }
  27.         } else {
  28.             map<int, long long> newcnt;
  29.             for (char c = 'a'; c <= 'z'; c++) {
  30.                 map<int, long long>::iterator it = cnt.begin();
  31.                 for (; it != cnt.end(); ++it) {
  32.                     // if we substitute '?' with char c,
  33.                     // then new hash value will be:
  34.                     int x = it->first + k * c % MOD;
  35.                     if (x >= MOD) {
  36.                         x -= MOD;
  37.                     }
  38.                     // and this new hash value can be reached from all
  39.                     // previous ones by adding char c:
  40.                     newcnt[x] += it->second;
  41.                     prev[q][x][0] = c;
  42.                     prev[q][x][1] = it->first;
  43.                 }
  44.             }
  45.             cnt.swap(newcnt);
  46.             q++;
  47.         }
  48.         k = (k*31) % MOD;
  49.     }
  50.  
  51.     if (cnt[code] != 1) {
  52.         // print number of solutions if not unique
  53.         cout << cnt[code];
  54.         return;
  55.     }
  56.  
  57.     // reconstruct unique solution
  58.     for (int i = 0; i < spell.size(); i++) {
  59.         if (spell[i] != '?') {
  60.             continue;
  61.         }
  62.         q--;
  63.         spell[i] = prev[q][code][0];
  64.         code = prev[q][code][1];
  65.     }
  66.     cout << spell;
  67. }
  68.  
  69. int main() {
  70.     int T; cin >> T;
  71.     for (int i = 0; i < T; i++) {
  72.         int code; cin >> code;
  73.         string spell; cin >> spell;
  74.         cout << "Case #" << i+1 << ": ";
  75.         solve(spell, code);
  76.         cout << endl;
  77.     }
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement