UVA - 817According to Bartjens

题意:给出一串数字,向里面插入“*”,“+”,“-”,使式子等于2000,至少要插入一个运算符。

分析:每个位置有4种情况不插入,“*”,“+”,“-”,最多有9个位置,每次枚举位置,最后判断输出。

# include<iostream>
# include<cstdio>
# include<cmath>
# include<map>
# include<queue>
# include<string>
# include<string.h>
#include<set>
#include<list>
# include<algorithm>
using namespace std;
int a[20];
char op[] = { '*','+','-' };
int len;
int res[20];
int reslen;
int ok = 0;
set<string>mp;
int ctoin(int s,int e) {
	int sum =a[s];
	for (int i = s+1; i <= e; i++) {
		sum = sum * 10 + a[i];
	}
	return sum;
}

int judge() {
	int ans = 0; int cnum[20]; int ncount = 0;
	int res1[20]; int res1len = 0;
	cnum[0] = a[0];
	for (int i = 0; i < len; i++) {
		if (res[i] == 3) {
			if (cnum[ncount] == 0)return 0;
			cnum[ncount] = cnum[ncount] * 10 + a[i+1];
		}
		else {
			cnum[++ncount] = a[i + 1];
			res1[res1len++] = res[i];
		}
	}
	int cnum2[20]; int ncount2 = 0;
	cnum2[0] = cnum[0];
	int res2[20]; int res2len = 0;
    for (int i = 0; i < res1len; i++) {//乘法优先
		if (res1[i] == 0) {
			cnum2[ncount2] *= cnum[i + 1];
		}
		else {
			res2[res2len++] = res1[i];
			cnum2[++ncount2] = cnum[i + 1];
		}
	}
	ans = cnum2[0];
	for (int i = 0; i < res2len; i++) {
		if (res2[i] == 1)
			ans += cnum2[i + 1];
		else
			ans -= cnum2[i + 1];
	}
	return ans;
}
void dfs(int pos) {
	if (pos == len) {
		if (judge() == 2000) {
			ok = 1;
			char ttt[20] = { 0 };
			ttt[0]= a[0]+'0';
			int k = 0;
			for (int j = 0; j < len; j++) {
				if (res[j] == 3) {
					ttt[++k]= a[j+1]+'0';
				}
				else {
					ttt[++k]= op[res[j]];
					ttt[++k]= a[j + 1]+'0';
				}
			}
			mp.insert(ttt);
		}
		return;
	}

	for (int i = 0; i < 4; i++) {
		res[pos] = i;
		dfs(pos + 1);
	}
	
}
void solve() {
	if (ctoin(0, len) == 2000) {
		cout << "  IMPOSSIBLE" << endl;
		return;
	}
	dfs(0);
	if(!ok)cout << "  IMPOSSIBLE" << endl;
	else {
		for (set<string>::iterator it = mp.begin(); it != mp.end(); ++it) {
			cout << "  " << (*it) << "=";
			cout << endl;
		}
	}
}
int main() {
	char k;
	int kase = 0;
	while (cin >> k && k != '=') {
		a[0] = k - '0'; len = 0; mp.clear();
		ok = 0;
		while (cin >> k && k != '=') {
			a[++len] = k-'0';
		}
		cout << "Problem " << ++kase<<endl;
		solve();
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值