留坑
#include<bits/stdc++.h> using namespace std; const int maxn=14; const int mod=99991; typedef long long ll; string s,t; int tol1=0,tol2=0,tol3=0; int a[maxn]; string tmp,path; unordered_set<string> st; typedef long long ll; int N,M; int tle=0; void dfs (int num,int sum) { //num表示当前已经用的数字数,sum表示当前表达式的值 if (num==N) { if (sum==M) { if (st.size()==0) path=tmp; st.insert(tmp); } return; } if (tol3) { for (int i=0;i<10;i++) { if (!a[i]) continue; tol3--; a[i]--; tmp.push_back(‘*‘);tmp.push_back(i+‘0‘); dfs(num+1,sum*i); tol3++; tmp.pop_back();tmp.pop_back(); a[i]++; } } if (tol1) { for (int i=0;i<10;i++) { if (!a[i]) continue; tol1--; a[i]--; tmp.push_back(‘+‘);tmp.push_back(i+‘0‘); dfs(num+1,sum+i); tol1++; tmp.pop_back();tmp.pop_back(); a[i]++; } } if (tol2) { for (int i=0;i<10;i++) { if (!a[i]) continue; tol2--; a[i]--; tmp.push_back(‘-‘);tmp.push_back(i+‘0‘); dfs(num+1,sum-i); tol2++; tmp.pop_back();tmp.pop_back(); a[i]++; } } } int main () { scanf("%d %d",&N,&M); cin>>s>>t; for (int i=0;i<t.length();i++) { if (t[i]==‘+‘) tol1++; if (t[i]==‘-‘) tol2++; if (t[i]==‘*‘) tol3++; } for (int i=0;i<s.length();i++) { a[s[i]-‘0‘]++; } for (int i=0;i<10;i++) { if (a[i]) { a[i]--; tmp.push_back(i+‘0‘); dfs(1,i); a[i]++; tmp.pop_back(); } } printf ("%d\n",st.size()); if (!st.size()) printf ("Impossible"); else cout<<path; return 0; }
原文地址:https://www.cnblogs.com/zhanglichen/p/12343891.html
时间: 2024-10-16 02:48:55