题意:
四个数字,可以改变顺序,中间可以添加+,-,*符号。数字之间还可以合并成一个数。
求最终能生成多少个数字。
思路:
暴力枚举生成了哪几个数,再枚举这几个数之间符号是啥,再用栈算出这个结果,用set去重。
写的贼麻烦,快麻了。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5+10;
set<int>st;
int get(deque<pair<int,int>>que) {
deque<pair<int,int>>d = que;
deque<pair<int,int>>now;
while(!que.empty()) {
pair<int,int>num = que.front();que.pop_front();
if(num.first == 1 && num.second == 2) {
pair<int,int>nex = que.front();que.pop_front();
pair<int,int>pre = now.back();now.pop_back();
int number = nex.second * pre.second;
now.push_back({0,number});
} else {
now.push_back(num);
}
}
que = now;
now.clear();
while(!que.empty()) {
pair<int,int>num = que.front();que.pop_front();
if(num.first == 1) {
if(num.second == 0) {
pair<int, int> nex = que.front();
que.pop_front();
pair<int, int> pre = now.back();
now.pop_back();
int number = nex.second + pre.second;
now.push_back({0,number});
} else if(num.second == 1) {
pair<int, int> nex = que.front();
que.pop_front();
pair<int, int> pre = now.back();
now.pop_back();
int number = pre.second - nex.second;
now.push_back({0,number});
}
} else {
now.push_back(num);
}
}
return now.front().second;
}
void fuhao(int id,vector<int>v,deque<pair<int,int>>que) {
if(id == v.size() - 1) {
que.push_back({0,v[id]});
int num = get(que);
if(num >= 0) {
st.insert(num);
}
return ;
}
que.push_back({0,v[id]});
for(int i = 0;i < 3;i++) { //+ - *
que.push_back({1,i});
fuhao(id + 1,v,que);
que.pop_back();
}
}
void cal(vector<int>v) {
if(v.size() == 1) return;
deque<pair<int,int>>que;
fuhao(0,v,que);
}
vector<vector<int>>vec;
int a[10];
void dfs(int id,int now,vector<int>v) {
if(id == 5) {
if(now) v.push_back(now);
vec.push_back(v);
return;
}
if(now) v.push_back(now);
dfs(id + 1,a[id],v);
if(now) v.pop_back();
now = now * 10 + a[id];
dfs(id + 1,now,v);
}
int main() {
scanf("%d%d%d%d",&a[1],&a[2],&a[3],&a[4]);
sort(a + 1,a + 1 + 4);
do {
vector<int> v;
dfs(1, 0, v);
}while(next_permutation(a + 1,a + 1 + 4));
for(int i = 0;i < vec.size();i++) {
cal(vec[i]);
}
printf("%d\n",st.size());
return 0;
}