AOJ - Problem 0043 : Puzzle

麻雀の役判定のような問題です。最初に2つ同じ数字のペアを決め、のこりを全探索で3個の数字の組み合わせ4つになるか調べるようにしました。同じ数字は4つまでしか使えないことに注意しましょう。

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int check(vector<int> a){
	int s=0;
	for(int i=0 ; i < a.size() ; i++ ){
		s += a[i];
	}
	return s;
}

void solve(vector<int> a, int n, int ans[10] ){
	if( check(a) == 0 ){
		ans[n] = 1;
		return;
	}

	for(int i=1; i <= 9 ; i++ ){
		if( a[i] >= 3 ){
			a[i] -= 3;
			solve( a , n , ans );
			a[i] += 3;
		}
	}
	for(int i=3 ; i <= 9 ; i++ ){
		if( a[i-2] && a[i-1] && a[i] ){
			a[i-2]--;
			a[i-1]--;
			a[i]--;
			solve( a , n , ans );
			a[i-2]++;
			a[i-1]++;
			a[i]++;
		}
	}
}

int main(){
	string s;
	while( cin >> s ){
		vector<int> a;
		int ans[10] = {0};
		for(int i=0 ; i <= 9 ; i++ ){
			a.push_back( 0 );
		}
		for(int i=0 ; i < s.size() ; i++ ){
			a[s[i]-'0']++;
		}

		for(int i=1 ; i <= 9 ; i++ ){
			if( a[i] == 4 ){
				continue;
			}else{
				a[i]++;
				for(int j=1 ; j <= 9 ; j++ ){
					if( a[j] >= 2 ){
						a[j] -= 2;
						solve( a , i , ans );
						a[j] += 2;
					}
				}
				a[i]--;
			}
		}

		bool NA = true;
		for(int i=1 ; i <= 9 ; i++ ){
			if( ans[i] ){
				NA = false;
			}
		}
		if( NA ){
			cout << 0 << endl;
		}else{
			bool flag = true;
			for(int i=1 ; i <= 9 ; i++ ){
				if( ans[i] == 1 ){
					if( flag ){
						flag = false;
					}else{
						cout << " ";
					}
					cout << i;
				}
			}
			cout << endl;
		}
	}
}

AOJ - Problem 1109 : Fermat's Last Theorem

1

#include <iostream>
#include <algorithm>
using namespace std;

int main(){
	int z;
	while( cin >> z , z ){
		long long int ans = -1;
		for(long long int x = 1 ; x*x*x < z*z*z ; x++ ){
			for(long long int y=1 ; x*x*x + y*y*y < z*z*z ; y++ ){
				long long int s = z*z*z - x*x*x - y*y*y;
				ans = ( ans == -1 )? s : min( ans , s );
			}
		}
		cout << ans << endl;
	}
}