UVA - 817According to Bartjens
生活随笔
收集整理的這篇文章主要介紹了
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];elseans -= 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();} }?
總結
以上是生活随笔為你收集整理的UVA - 817According to Bartjens的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UVA - 1533Moving Peg
- 下一篇: 高僧斗法(博弈论)