Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <cmath>
- #include <map>
- using namespace std;
- int num_white_pawns, num_black_pawns;
- bool check_pawns(vector<int> & pawns) {
- int cnt_white = 0;
- for(int i = 0; i < pawns.size(); i++) {
- if(pawns[i] != 1) {
- break;
- }
- cnt_white++;
- }
- if(cnt_white != num_white_pawns) {
- return false;
- }
- int cnt_black = 0;
- for(int i = pawns.size() - 1; i >= 0; i--) {
- if(pawns[i] != 2) {
- break;
- }
- cnt_black++;
- }
- if(cnt_black != num_black_pawns) {
- return false;
- }
- return true;
- }
- int main() {
- int n;
- cin >> n;
- num_white_pawns = 0;
- num_black_pawns = 0;
- vector<int> v(n);
- map<vector<int>, bool> visited;
- for(int i = 0; i < n; i++) {
- cin >> v[i];
- if(v[i] == 1) {
- num_white_pawns++;
- }
- if(v[i] == 2) {
- num_black_pawns++;
- }
- }
- visited[v] = true;
- queue<vector<int>> q;
- q.push(v);
- queue<int> q_dist;
- q_dist.push(0);
- queue<vector<int>> steps;
- steps.push({});
- while(!q.empty()) {
- vector<int> c = q.front();
- q.pop();
- int dist = q_dist.front();
- q_dist.pop();
- vector<int> v_steps = steps.front();
- steps.pop();
- if(check_pawns(c)) {
- cout << dist << endl;
- for(int i = 0; i < v_steps.size(); i++) {
- cout << v_steps[i] << " ";
- }
- break;
- }
- for(int i = 0; i < n; i++) {
- if(c[i] == 1) {
- if(i - 1 >= 0 and c[i - 1] == 0) {
- swap(c[i], c[i - 1]);
- if(!visited[c]) {
- q.push(c);
- q_dist.push(dist + 1);
- visited[c] = true;
- vector<int> tmp = v_steps;
- tmp.push_back(i + 1);
- steps.push(tmp);
- }
- swap(c[i], c[i - 1]);
- }
- if(i - 2 >= 0 and c[i - 1] != 0 and c[i - 2] == 0) {
- swap(c[i], c[i - 2]);
- if(!visited[c]) {
- q.push(c);
- q_dist.push(dist + 1);
- visited[c] = true;
- vector<int> tmp = v_steps;
- tmp.push_back(i + 1);
- steps.push(tmp);
- }
- swap(c[i], c[i - 2]);
- }
- }
- else if(c[i] == 2) {
- if(i + 1 < n and c[i + 1] == 0) {
- swap(c[i], c[i + 1]);
- if(!visited[c]) {
- visited[c] = true;
- q.push(c);
- q_dist.push(dist + 1);
- vector<int> tmp = v_steps;
- tmp.push_back(i + 1);
- steps.push(tmp);
- }
- swap(c[i], c[i + 1]);
- }
- if(i + 2 < n and c[i + 1] != 0 and c[i + 2] == 0) {
- swap(c[i], c[i + 2]);
- if(!visited[c]) {
- visited[c] = true;
- q.push(c);
- q_dist.push(dist + 1);
- vector<int> tmp = v_steps;
- tmp.push_back(i + 1);
- steps.push(tmp);
- }
- swap(c[i], c[i + 2]);
- }
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement