sgu 249

在知道格雷码的递归生成算法的前提下,这题就不难了。

格雷码的递归生成算法 =>   http://my.oschina.net/mustang/blog/57392

 

#include <vector>
#include <cstdio>
#include <algorithm>
using namespace std;

template <class VVType, class T>
void make2DVector(VVType & a, int d, int f, const T & initValue) {
    int i, j;
    a.resize(d);
    for (i = 0; i < d; ++i) {
        a[i].resize(f);
        for (j = 0; j < f; ++j) a[i][j] = initValue;
    }
}



template <class VVType>
void doubleSizeH(int rowNum, int colNum, VVType & src, VVType & dest) {
  int a, b, c, d, x, s0, s1;

  b = 0; d = 0;
  while(1) {

    if (b >= colNum) break;

    a = 0;
    c = 0;
    s0 = 0;
    s1 = 1;

    while(1) {
      if (a >= rowNum) break;
      int x = src[a][b];
      dest[c][d] = x * 2 + s0;
      dest[c + 1][d] = x * 2 + s1;

      a += 1;
      c += 2;
      swap(s0, s1);
    }

    b += 1;
    d += 1;

  }

}

template <class VVType>
void doubleSizeW(int rowNum, int colNum, VVType & src, VVType & dest) {
  int a, b, c, d, x, s0, s1;

  a = 0; c = 0;
  while(1) {

    if ( a >= rowNum) break;

    b = 0;
    d = 0;
    s0 = 0;
    s1 = 1;

    while(1) {
      if (b >= colNum) break;
      int x = src[a][b];
      dest[c][d] = x * 2 + s0;
      dest[c][d + 1] = x * 2 + s1;

      b += 1;
      d += 2;
      swap(s0, s1);
    }

    a += 1;
    c += 1;
  }

}

int N, M;
vector< vector<int> > W[2];


void input() {
  scanf("%d %d", &N, &M);
  make2DVector(W[0], 1 << N, 1 << M, 0);
  make2DVector(W[1], 1 << N, 1 << M, 0);
}

void run() {
  input();
  int curRowNum = 1;
  int curColNum = 1;
  int k = 0;
  W[0][0][0] = 0;
  int i, j;

  for (i = 0; i < N; ++i) {
    doubleSizeH(curRowNum, curColNum, W[k], W[1-k]);
    k = 1 - k;
    curRowNum *= 2;
  }

  for (i = 0; i < M; ++i) {
    doubleSizeW(curRowNum, curColNum, W[k], W[1-k]);
    k = 1 - k;
    curColNum *= 2;
  }

  int lastRow = (1 << N) - 1;
  int lastCol = (1 << M) - 1;
  for (i = 0; i <= lastRow; ++i) {
    for (j = 0; j <= lastCol; ++ j) {
      if (j == lastCol) printf("%d\n", W[k][i][j]);
      else printf("%d ", W[k][i][j]);
    }
  }
}


int main() {
  run();
  return 0;
}

你可能感兴趣的:(sgu 249)