結果
| 問題 |
No.2069 み世界数式
|
| ユーザー |
|
| 提出日時 | 2022-08-16 15:44:33 |
| 言語 | C++23 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 47 ms / 2,000 ms |
| コード長 | 2,575 bytes |
| コンパイル時間 | 2,796 ms |
| コンパイル使用メモリ | 253,084 KB |
| 実行使用メモリ | 9,336 KB |
| 最終ジャッジ日時 | 2024-11-24 16:08:32 |
| 合計ジャッジ時間 | 5,026 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 41 |
ソースコード
#include<bits/stdc++.h>
using namespace std;
int m,ans;
string expr;
bool dp[3][1001][301];
int op1[2][1001][301],op2[2][1001][301];
char op[2][1001][301];
vector<pair<int,int>>chr[3][1001];
int expr1(int n);
int term1(int n);
int factor1(int n);
void expr2(int n,int ans);
void term2(int n,int ans);
void factor2(int n,int ans);
int expr1(int n){
auto&ch=chr[0][n];
ch.push_back({n,-1});
n=term1(n);
ch.back().second=n;
copy(dp[1][n],dp[1][n]+m+1,dp[0][n]);
while(n<expr.size()&&expr[n]=='$'){
int bef=n;
n++;
ch.push_back({n,-1});
n=term1(n);
ch.back().second=n;
for(int i=0;i<=m;i++){
for(int j=0;j<=m;j++){
if(dp[0][bef][i]&&dp[1][n][j]&&i+j<=m){
dp[0][n][i+j]=1;
op1[0][n][i+j]=i;
op2[0][n][i+j]=j;
op[0][n][i+j]='+';
}
if(dp[0][bef][i]&&dp[1][n][j]&&i-j>=0){
dp[0][n][i-j]=1;
op1[0][n][i-j]=i;
op2[0][n][i-j]=j;
op[0][n][i-j]='-';
}
}
}
}
return n;
}
int term1(int n){
auto&ch=chr[1][n];
ch.push_back({n,-1});
n=factor1(n);
ch.back().second=n;
copy(dp[2][n],dp[2][n]+m+1,dp[1][n]);
while(n<expr.size()&&expr[n]=='&'){
int bef=n;
n++;
ch.push_back({n,-1});
n=factor1(n);
ch.back().second=n;
for(int i=0;i<=m;i++){
for(int j=0;j<=m;j++){
if(dp[1][bef][i]&&dp[2][n][j]&&i*j<=m){
dp[1][n][i*j]=1;
op1[1][n][i*j]=i;
op2[1][n][i*j]=j;
op[1][n][i*j]='*';
}
if(dp[1][bef][i]&&dp[2][n][j]&&j!=0){
dp[1][n][i/j]=1;
op1[1][n][i/j]=i;
op2[1][n][i/j]=j;
op[1][n][i/j]='/';
}
}
}
}
return n;
}
int factor1(int n){
if(isdigit(expr[n])){
int num=0;
while(n<expr.size()&&isdigit(expr[n])){
num=num*10+expr[n]-'0';
n++;
}
dp[2][n][num]=1;
}else{
auto&ch=chr[2][n];
n++;
ch.push_back({n,-1});
n=expr1(n);
ch.back().second=n;
n++;
copy(dp[0][n-1],dp[0][n-1]+m+1,dp[2][n]);
}
return n;
}
void expr2(int n,int ans){
auto&ch=chr[0][n];
for(int i=ch.size()-1;i>=1;i--){
term2(ch[i].first,op2[0][ch[i].second][ans]);
expr[ch[i-1].second]=op[0][ch[i].second][ans];
ans=op1[0][ch[i].second][ans];
}
term2(n,ans);
}
void term2(int n,int ans){
auto&ch=chr[1][n];
for(int i=ch.size()-1;i>=1;i--){
factor2(ch[i].first,op2[1][ch[i].second][ans]);
expr[ch[i-1].second]=op[1][ch[i].second][ans];
ans=op1[1][ch[i].second][ans];
}
factor2(n,ans);
}
void factor2(int n,int ans){
auto&ch=chr[2][n];
if(!ch.empty())
expr2(ch[0].first,ans);
}
int main(){
cin>>m>>ans>>expr;
expr1(0);
if(!dp[0][expr.size()][ans]){
cout<<-1<<endl;
return 0;
}
expr2(0,ans);
cout<<expr<<endl;
}