[Coursera]算法基础_Week2_枚举_Q2

来源:互联网 发布:买口红热 知乎 编辑:程序博客网 时间:2024/06/04 05:02
#include <iostream>using namespace std;#define INF 1000000int opn = 0;void Op(int temp[9], int op[9]) {for (int i = 0; i < 9; i++) {if (op[i] != 0) {for (int j = 0; j < op[i]; j++) {if (i == 0) {temp[0]++; temp[1]++; temp[3]++; temp[4]++;}else if (i == 1) {temp[0]++; temp[1]++; temp[2]++;}else if (i == 2) {temp[1]++; temp[2]++; temp[4]++; temp[5]++;}else if (i == 3) {temp[0]++; temp[3]++; temp[6]++;}else if (i == 4) {temp[1]++; temp[3]++; temp[4]++; temp[5]++; temp[7]++;}else if (i == 5) {temp[2]++; temp[5]++; temp[8]++;}else if (i == 6) {temp[3]++; temp[4]++; temp[6]++; temp[7]++;}else if (i == 7) {temp[6]++; temp[7]++; temp[8]++;}else if (i == 8) {temp[4]++; temp[5]++; temp[7]++; temp[8]++;}}}}for (int i = 0; i < 9; i++) {opn += op[i];}}int main() {int clock[9] = { 0 };int temp[9] = { 0 };int op[9] = { 0 };for (int i = 0; i < 9; i++) {cin >> clock[i];}int z = 1;for (int i = 0; i < 9; i++)z *= 4;int Z = z;int *p = new int[z];while (z--) {int t = z;for (int i = 0; i < 9; i++) {op[i] = t % 4;t /= 4;}for (int i = 0; i < 9; i++) {temp[i] = clock[i];}Op(temp, op);int f = 1;for (int i = 0; i < 9; i++) {if (temp[i] % 4 != 0)f = 0;}if (f)p[z] = opn;elsep[z] = INF;opn = 0;}int res = INF;int Id = 0;for (int i = 0; i < Z; i++) {if (res > p[i]) {res = p[i];Id = i;}}if (res == INF)cout << "inf" << endl;else {int t = Id;for (int i = 0; i < 9; i++) {op[i] = t % 4;t /= 4;}for (int i = 0; i < 9; i++) {if (op[i] != 0) {for (int j = 0; j < op[i]; j++) {if(j==op[i]-1&&i==8)cout << i + 1 << endl;elsecout << i + 1 << ' ';}}}}delete[]p;return 0;}

0 0
原创粉丝点击