programming-challenges Hanoi Tower Troubles Again! (110908) 题解

贪心算法就可以简单的解决了。但是问题是如何我没有办法证明贪心是对的。

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <assert.h>
#include <algorithm>
#include <math.h>
#include <ctime>
#include <functional>
#include <string.h>
#include <stdio.h>
#include <numeric>
#include <float.h>

using namespace std;

bool isSquare(int num) {
	int i = sqrt(num); 
	if (num == i*i) return true;
	return false;
}

int solution(int colNum) {
	vector<int> colums(colNum); 
	int num = 0, ans = 0;
	while (true) {
		num++;
		bool ok = false; 
		for (int i = 0; i < colNum; i++) {
			if (colums[i] == 0) {
				colums[i] = num;
				ok = true;
				ans++; 
				break;
			}
			else {
				if (isSquare(colums[i] + num)) {
					colums[i] = num; 
					ok = true;
					ans++; 
					break;
				}
			}
		}
		if (!ok) break;
	}
	return ans; 
}

int main() {
	int T = 0; cin >> T; 

	for (int t = 0; t < T; t++) {
		int colNum; cin >> colNum; 
		cout << solution(colNum) << endl; 
	}

	return 0;
}


你可能感兴趣的:(Algorithm,C++)