Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<iostream>
  3. #include<algorithm>
  4. #include<string>
  5. #include<string.h>
  6. #include<stdlib.h>
  7. #include<vector>
  8. #include<math.h>
  9. #include<map>
  10. #include<queue>
  11. using namespace std;
  12.  
  13. bool check(string s){
  14.     int n = (int)s.length();
  15.     for(int i=0;i<n-3;i++){
  16.         if(s.substr(i,4) == "2012") return true;
  17.     }
  18.     return false;
  19. }
  20. int main(){
  21.     int n;
  22.     string s;
  23.     cin>>n>>s;
  24.     map<string,int> mp;
  25.     queue<string> q;
  26.     q.push(s);
  27.     int res = -1;
  28.     mp[s] = 0;
  29.     string ns;
  30.     while(!q.empty()){
  31.         string top = q.front();
  32.         q.pop();
  33.         if(check(top)){
  34.             res = mp[top];
  35.             break;
  36.         }
  37.         int n = (int)top.length();
  38.         int step = mp[top];
  39.         for(int i=0;i<n-1;i++){
  40.             swap(top[i], top[i+1]);
  41.             if(mp.find(top) == mp.end()){
  42.                 q.push(top);
  43.                 mp[top] = step+1;
  44.             }
  45.             swap(top[i], top[i+1]);
  46.         }
  47.     }
  48.  
  49.     printf("%d\n",res);
  50.  
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement