[4_4_shuttle] Search? Analyze?

Shuttle Puzzle
Traditional

The Shuttle Puzzle of size 3 consists of 3 white marbles, 3 black marbles, and a strip of wood with 7 holes. The marbles of the same color are placed in the holes at the opposite ends of the strip, leaving the center hole empty.

 
INITIAL STATE: WWW_BBB 
GOAL STATE: BBB_WWW

To solve the shuttle puzzle, use only two types of moves. Move 1 marble 1 space (into the empty hole) or jump 1 marble over 1 marble of the opposite color (into the empty hole). You may not back up, and you may not jump over 2 marbles.

A Shuttle Puzzle of size N consists of N white marbles and N black marbles and 2N+1 holes.

Here's one solution for the problem of size 3 showing the initial, intermediate, and end states:

 
WWW BBB
WW WBBB
WWBW BB
WWBWB B
WWB BWB
W BWBWB
 WBWBWB
BW WBWB
BWBW WB
BWBWBW 
BWBWB W
BWB BWW
B BWBWW
BB WBWW
BBBW WW
BBB WWW

Write a program that will solve the SHUTTLE PUZZLE for any size N (1 <= N <= 12) in the minimum number of moves and display the successive moves, 20 per line.

PROGRAM NAME: shuttle

INPUT FORMAT

A single line with the integer N.

SAMPLE INPUT (file shuttle.in)

 
3

OUTPUT FORMAT

The list of moves expressed as space-separated integers, 20 per line (except possibly the last line). Number the marbles/holes from the left, starting with one.

Output the the solution that would appear first among the set of minimal solutions sorted numerically (first by the first number, using the second number for ties, and so on).

SAMPLE OUTPUT (file shuttle.out)

 
3 5 6 4 2 1 3 5 7 6 4 2 3 5 4
























My solution: search! (+ greedy)
First attempt: BFS + use STL string, map, vector to store results
#include <algorithm>
#include <climits>
#include <cstdio>
#include <fstream>
#include <map>
#include <queue>
#include <string>
#include <utility>
#include <vector>

using namespace std;

int main() {
        ifstream fin("shuttle.in");
        int n;
        fin >> n;
        fin.close();

        char buf[BUFSIZ] = {};
        for (int i = 0; i < n; ++i)
                buf[i] = 'W', buf[n + i] = 'B';
        const string source = string(buf);
        reverse(buf, buf + 2 * n);
        const string target = string(buf);

        int ans_depth = INT_MAX, idx = -1;
        vector<int> ans_vec;
        vector<pair<pair<string, int>, int> > ans;
        map<pair<string, int>, int> hash;
        hash[make_pair(source, n)] = idx;
        queue<pair<pair<string, int>, int> > q;
        q.push(make_pair(make_pair(source, n), 0));
        while (!q.empty()) {
                string str = q.front().first.first;
                int num = q.front().first.second;
                int depth = q.front().second;
                if (depth > ans_depth)
                        break;
                ans.push_back(q.front());
                ++idx;
                q.pop();
                if (num == n && str == target) {
                        ans_depth = depth;
                        vector<int> vec;
                        while (depth != 0) {
                                vec.push_back(num + 1);
                                pair<string, int> tuple = make_pair(str, num);
                                int j = hash[tuple];
                                str = ans[j].first.first;
                                num = ans[j].first.second;
                                depth = ans[j].second;
                        }
                        if (ans_vec.size() == 0) {
                                for (int j = ans_depth - 1; j >= 0; --j)
                                        ans_vec.push_back(vec[j]);
                        } else {
                                vector<int> tmp;
                                for (int j = ans_depth - 1; j >= 0; --j)
                                        tmp.push_back(vec[j]);
                                bool flag = false;
                                for (int j = 0; j < ans_depth; ++j)
                                        if (tmp[j] < ans_vec[j])
                                                flag = true;
                                if (flag)
                                        ans_vec = tmp;
                        }
                        continue;
                }
                if (depth == ans_depth) continue;
                pair<string, int> tuple;
                int tmp = num - 1;
                tuple = make_pair(str, tmp);
                if (tmp >= 0 && hash.find(tuple) == hash.end()) {
                        hash[tuple] = idx;
                        q.push(make_pair(tuple, depth + 1));
                }
                tmp = num + 1;
                tuple = make_pair(str, tmp);
                if (tmp <= 2 * n && hash.find(tuple) == hash.end()) {
                        hash[tuple] = idx;
                        q.push(make_pair(tuple, depth + 1));
                }
                if (num + 2 <= 2 * n && str[num] != str[num + 1]) {
                        string s = str;
                        swap(s[num], s[num + 1]);
                        tuple = make_pair(s, num + 2);
                        if (hash.find(tuple) == hash.end()) {
                                hash[tuple] = idx;
                                q.push(make_pair(tuple, depth + 1));
                        }
                }
                if (num - 2 >= 0 && str[num - 1] != str[num - 2]) {
                        string s = str;
                        swap(s[num - 1], s[num - 2]);
                        tuple = make_pair(s, num - 2);
                        if (hash.find(tuple) == hash.end()) {
                                hash[tuple] = idx;
                                q.push(make_pair(tuple, depth + 1));
                        }
                }
        }

        ofstream fout("shuttle.out");
        for (int i = 0; i < ans_depth; ++i)
                fout << ans_vec[i] << ((i == ans_depth - 1 || (i + 1) % 20 == 0) ? '\n' : ' ');
        fout.close();

        return 0;
}

Second attempt:
Use bit operations to save space and speed up! (MLE on test case #5 or #6)
#include <algorithm>
#include <climits>
#include <cstdio>
#include <fstream>
#include <map>
#include <utility>
#include <vector>

using namespace std;

const int NUM = 1000000;
int q_str[NUM], q_dep[NUM], q_num[NUM];

int main() {
        ifstream fin("shuttle.in");
        int n;
        fin >> n;
        fin.close();

        int temp = 1, binary[25] = {1};
        for (int i = 0; i < 25; ++i)
                binary[i] = temp, temp = (temp << 1);
        temp = 0;
        for (int i = 0; i < n; ++i)
                temp |= binary[n + i];
        const int source = temp;
        temp = 0;
        for (int i = 0; i < n; ++i)
                temp |= binary[i];
        const int target = temp;

        int ans_depth = INT_MAX;
        vector<int> ans_vec;
        map<pair<int, int>, int> hash;
        int front = 0, rear = 1;
        hash[make_pair(source, n)] = front - 1;
        q_str[0] = source, q_num[0] = n, q_dep[0] = 0;
        while (front < rear) {
                int str = q_str[front];
                int num = q_num[front];
                int depth = q_dep[front];
                if (depth > ans_depth)
                        break;
                ++front;
                if (num == n && str == target) {
                        ans_depth = depth;
                        vector<int> vec;
                        while (depth != 0) {
                                vec.push_back(num + 1);
                                pair<int, int> tuple = make_pair(str, num);
                                int j = hash[tuple];
                                str = q_str[j];
                                num = q_num[j];
                                depth = q_dep[j];
                        }
                        if (ans_vec.size() == 0) {
                                for (int j = ans_depth - 1; j >= 0; --j)
                                        ans_vec.push_back(vec[j]);
                        } else {
                                vector<int> tmp;
                                for (int j = ans_depth - 1; j >= 0; --j)
                                        tmp.push_back(vec[j]);
                                bool flag = false;
                                for (int j = 0; j < ans_depth; ++j)
                                        if (tmp[j] < ans_vec[j])
                                                flag = true;
                                if (flag)
                                        ans_vec = tmp;
                        }
                        continue;
                }
                if (depth == ans_depth) continue;
                pair<int, int> tuple;
                int tmp = num - 1;
                tuple = make_pair(str, tmp);
                if (tmp >= 0 && hash.find(tuple) == hash.end()) {
                        hash[tuple] = front - 1;
                        q_str[rear] = str;
                        q_num[rear] = tmp;
                        q_dep[rear] = depth + 1;
                        ++rear;
                }
                tmp = num + 1;
                tuple = make_pair(str, tmp);
                if (tmp <= 2 * n && hash.find(tuple) == hash.end()) {
                        hash[tuple] = front - 1;
                        q_str[rear] = str;
                        q_num[rear] = tmp;
                        q_dep[rear] = depth + 1;
                        ++rear;
                }
                if (num + 2 <= 2 * n && (str & binary[num]) != (str & binary[num + 1])) {
                        int s = str;
                        s = (s ^ binary[num] ^ binary[num + 1]);
                        tuple = make_pair(s, num + 2);
                        if (hash.find(tuple) == hash.end()) {
                                hash[tuple] = front - 1;
                                q_str[rear] = s;
                                q_num[rear] = num + 2;
                                q_dep[rear] = depth + 1;
                                ++rear;
                        }
                }
                if (num - 2 >= 0 && (str & binary[num - 1]) != (str & binary[num - 2])) {
                        int s = str;
                        s = (s ^ binary[num - 1] ^ binary[num - 2]);
                        tuple = make_pair(s, num - 2);
                        if (hash.find(tuple) == hash.end()) {
                                hash[tuple] = front - 1;
                                q_str[rear] = s;
                                q_num[rear] = num - 2;
                                q_dep[rear] = depth + 1;
                                ++rear;
                        }
                }
        }

        ofstream fout("shuttle.out");
        for (int i = 0; i < ans_depth; ++i)
                fout << int(ans_vec[i]) << ((i == ans_depth - 1 || (i + 1) % 20 == 0) ? '\n' : ' ');
        fout.close();

        return 0;
}

Final try:
Greedy: Black only goes left, and White only goes right ( http://www.nocow.cn/index.php/USACO/shuttle)
Use unsigned char to save space (otherwise Memory Limit Exceeded)
Queue size: less than 350000 for n = 12
#include <algorithm>
#include <climits>
#include <cstdio>
#include <fstream>
#include <map>
#include <utility>
#include <vector>

using namespace std;

typedef unsigned char uchar;

const int NUM = 350000;
int q_str[NUM];
uchar q_num[NUM], q_dep[NUM];

int main() {
        ifstream fin("shuttle.in");
        int n;
        fin >> n;
        fin.close();

        int temp = 1, binary[25] = {1};
        for (int i = 0; i < 25; ++i)
                binary[i] = temp, temp = (temp << 1);
        temp = 0;
        for (int i = 0; i < n; ++i)
                temp |= binary[i];
        const int source = temp;
        temp = 0;
        for (int i = 0; i < n; ++i)
                temp |= binary[n + i];
        const int target = temp;

        int ans_depth = INT_MAX;
        vector<uchar> ans_vec;
        map<pair<int, uchar>, int> hash;
        int front = 0, rear = 1;
        hash[make_pair(source, n)] = front - 1;
        q_str[0] = source, q_num[0] = n, q_dep[0] = 0;
        while (front < rear) {
                int str = q_str[front];
                uchar num = q_num[front];
                uchar depth = q_dep[front];
                if (depth > ans_depth)
                        break;
                ++front;
                if (num == n && str == target) {
                        ans_depth = depth;
                        vector<uchar> vec;
                        while (depth != 0) {
                                vec.push_back(num + 1);
                                pair<int, uchar> tuple = make_pair(str, num);
                                int j = hash[tuple];
                                str = q_str[j];
                                num = q_num[j];
                                depth = q_dep[j];
                        }
                        if (ans_vec.size() == 0) {
                                for (int j = ans_depth - 1; j >= 0; --j)
                                        ans_vec.push_back(vec[j]);
                        } else {
                                vector<uchar> tmp;
                                for (int j = ans_depth - 1; j >= 0; --j)
                                        tmp.push_back(vec[j]);
                                bool flag = false;
                                for (int j = 0; j < ans_depth; ++j)
                                        if (tmp[j] < ans_vec[j])
                                                flag = true;
                                if (flag)
                                        ans_vec = tmp;
                        }
                        continue;
                }
                if (depth == ans_depth) continue;
                pair<int, uchar> tuple;
                char tmp = num - 1;
                tuple = make_pair(str, tmp);
                if (tmp >= 0 && (str & binary[tmp]) == binary[tmp] && hash.find(tuple) == hash.end()) {
                        hash[tuple] = front - 1;
                        q_str[rear] = str;
                        q_num[rear] = tmp;
                        q_dep[rear] = depth + 1;
                        ++rear;
                }
                tmp = num + 1;
                tuple = make_pair(str, tmp);
                if (tmp <= 2 * n && (str & binary[num]) == 0 && hash.find(tuple) == hash.end()) {
                        hash[tuple] = front - 1;
                        q_str[rear] = str;
                        q_num[rear] = tmp;
                        q_dep[rear] = depth + 1;
                        ++rear;
                }
                if (num + 2 <= 2 * n && (str & binary[num]) == binary[num] && (str & binary[num]) != (str & binary[num + 1])) {
                        int s = str;
                        s = (s ^ binary[num] ^ binary[num + 1]);
                        tuple = make_pair(s, num + 2);
                        if (hash.find(tuple) == hash.end()) {
                                hash[tuple] = front - 1;
                                q_str[rear] = s;
                                q_num[rear] = num + 2;
                                q_dep[rear] = depth + 1;
                                ++rear;
                        }
                }
                if (num - 2 >= 0 && (str & binary[num - 1]) == 0 && (str & binary[num - 1]) != (str & binary[num - 2])) {
                        int s = str;
                        s = (s ^ binary[num - 1] ^ binary[num - 2]);
                        tuple = make_pair(s, num - 2);
                        if (hash.find(tuple) == hash.end()) {
                                hash[tuple] = front - 1;
                                q_str[rear] = s;
                                q_num[rear] = num - 2;
                                q_dep[rear] = depth + 1;
                                ++rear;
                        }
                }
        }
        //printf("front = %d, depth = %d\n", front, ans_depth);

        ofstream fout("shuttle.out");
        for (int i = 0; i < ans_depth; ++i)
                fout << int(ans_vec[i]) << ((i == ans_depth - 1 || (i + 1) % 20 == 0) ? '\n' : ' ');
        fout.close();

        //system("pause");
        return 0;
}
Results:
Executing...
   Test 1: TEST OK [0.000 secs, 5552 KB]
   Test 2: TEST OK [0.000 secs, 5552 KB]
   Test 3: TEST OK [0.000 secs, 5552 KB]
   Test 4: TEST OK [0.000 secs, 5552 KB]
   Test 5: TEST OK [0.000 secs, 5552 KB]
   Test 6: TEST OK [0.011 secs, 5552 KB]
   Test 7: TEST OK [0.022 secs, 5552 KB]
   Test 8: TEST OK [0.054 secs, 7664 KB]
   Test 9: TEST OK [0.151 secs, 5552 KB]
   Test 10: TEST OK [0.367 secs, 16376 KB]













Official solution: Analysis method
Shuttle Puzzle
Hal Burch

Examine the form the sample output gives:

The black squares that outline the moved marble in the sample solution form a pattern:
There are two parts of the pattern, the expanding portion and the contracting portion. The boundary of the movement expands by one each pass in the expanding portion, and contracts by one each pass in the contracting portion. In each pass, the selection moves two until it reaches the other end of the boundary, and then goes moves to the new boundary. This pattern can be calculated and outputted to produce the optimal answer.

Since each step can be computing in constant time, this algorithm should run easily within time.

 
 
#include <stdio.h>

#define MAXS 32

int size;  /* `size' of board, in terms of number of black marbles */
int bsize; /* real size of board, in terms of holes */
int eloc;  /* location of empty hole */

FILE *fout, *fin;

void outmove(int i)
 {
  static int mcnt = 0;
  if (i == -1) /* possible newline needed at the end */
   {
    if (mcnt) fprintf (fout, "\n");
    return;
   }

  eloc = i;
  fprintf (fout, "%i", i+1); /* output the answer */
  /* handle spacing and newlines */
  if (++mcnt < 20) fprintf (fout, " ");
  else
   { 
    fprintf (fout, "\n");
    mcnt = 0;
   }
 }

int main(int argc, char **argv)
 {
  int lv, lv2;

  if ((fin = fopen("shuttle.in", "r")) == NULL)
   {
    perror ("fopen fin");
    exit(1);
   }
  if ((fout = fopen("shuttle.out", "w")) == NULL)
   {
    perror ("fopen fout");
    exit(1);
   }

  fscanf (fin, "%d", &size);

  eloc = size;
  bsize = 2*size+1;

  /* expansion phase of pattern */
  for (lv = 0; lv <= size; lv++)
   {
    if (lv % 2 == 0) /* even moves left */
     {
      for (lv2 = 0; lv2 < lv; lv2++)
        outmove(eloc-2);
      /* expand by one step */
      if (eloc-1 >= 0) outmove(eloc-1);
     } else { /* odd moves right */
      for (lv2 = 0; lv2 < lv; lv2++)
        outmove(eloc+2);
      /* expand by one step */
      if (eloc+1 < bsize) outmove(eloc+1);
     }
   }

  /* contraction phase of pattern */
  for (lv = size-1; lv >= 0; lv--)
   {
    if (eloc < size) /* if eloc is to left of center, move right */
     {
      outmove(eloc+1); /* contract by one step */
      for (lv2 = 0; lv2 < lv; lv2++)
        outmove(eloc+2);
     } else { /* if eloc is to the right of center, move left */
      outmove(eloc-1); /* contract by one step */
      for (lv2 = 0; lv2 < lv; lv2++)
        outmove(eloc-2);
     }
   }
  outmove(-1); /* clean-up newlines */
  return 0;
 }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值