1. 程式人生 > >According to Bartjens UVA

According to Bartjens UVA

很明顯的暴力列舉,列舉的過程中會遇到關於表示式計算的問題,在暴力列舉中算是一個常見的問題吧

程式碼參考別人的,看了之後感覺在表示式計算的方面還有可以改進的地方

關於改進的問題等表示式計算模板出來再去考慮吧

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iomanip>
#include<assert.h>
#include<vector>
#include<list>
#include<map>
#include<set>
#include<sstream>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
#pragma warning(disable:4996)
#define me(s)  memset(s,0,sizeof(s))
#define _for(i,a,b) for(int i=(a);i<(b);++i)
#define _rep(i,a,b) for(int i=(a);i<=(b);++i)
using namespace std;
typedef pair <int, int> pii;
typedef long long ll;
typedef unsigned long long llu;
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const double eps = 1e-15;
int c[3] = { '*','+','-' };
const int maxn = 25;
char str[maxn], re[maxn];
int res[maxn], n, flag;
set<string> ouput;
void init()
{
	ouput.clear();
	n = strlen(str) - 1;
	flag = 1;
}
int cal()
{
	int num[maxn], num1[maxn], ans = 0, numn = 0, i, numn1 = 0, res1[maxn], resn = 0, res2[maxn], res2n = 0;
	num[0] = str[0] - '0';
	for (i = 0; i < n - 1; i++) {
		if (res[i] == 3) {
			if (num[numn] == 0) return 0;
			num[numn] = num[numn] * 10 + str[i + 1] - '0';
		}
		else {
			res1[resn++] = res[i];
			num[++numn] = str[i + 1] - '0';
		}
	}
	num1[0] = num[0];
	for (i = 0; i < resn; i++) {
		if (res1[i] == 0) {
			num1[numn1] *= num[i + 1];
		}
		else {
			res2[res2n++] = res1[i];
			num1[++numn1] = num[i + 1];
		}
	}
	ans = num1[0];
	for (i = 0; i < res2n; i++)
		if (res2[i] == 1) ans += num1[i + 1];
		else ans -= num1[i + 1];
	return ans;
}
void dfs(int cur)
{
	if (cur == n - 1) {
		int num = cal();
		if (num == 2000) {
			flag = 0;
			me(re);
			int k = 1;
			re[0] = str[0];
			for (int j = 0; j < cur; j++) {
				if (res[j] == 3) re[k++] = str[j + 1];
				else {
					re[k++] = c[res[j]];
					re[k++] = str[j + 1];
				}
			}
			ouput.insert(re);
		}
		return;
	}
	for (int i = 0; i < 4; i++) {
		res[cur] = i;
		dfs(cur + 1);
	}
}
void solve()
{
	if (strcmp(str, "2000=") == 0) {
		printf("  IMPOSSIBLE\n");
		return;
	}
	dfs(0);
	if(flag) printf("  IMPOSSIBLE\n");
	else {
		for (auto it : ouput)
			cout << "  " << it << '=' << endl;
	}
}
int main()
{
	int kcase = 0;
	while (scanf("%s", str) == 1 && str[0] != '=')
	{
		init();
		printf("Problem %d\n", ++kcase);
		solve();
	}
}