[Coursera]演算法基礎_Week2_列舉_Q2

yiliu_cr發表於2015-12-13
#include <iostream>
using namespace std;
#define INF 1000000
int 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;
		else
			p[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;
					else
						cout << i + 1 << ' ';
				}
			}
		}
	}
	delete[]p;
	return 0;
}

相關文章