結果
| 問題 |
No.297 カードの数式
|
| コンテスト | |
| ユーザー |
@abcde
|
| 提出日時 | 2019-04-27 18:42:22 |
| 言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 3,647 bytes |
| コンパイル時間 | 1,852 ms |
| コンパイル使用メモリ | 171,864 KB |
| 実行使用メモリ | 6,820 KB |
| 最終ジャッジ日時 | 2024-11-29 01:09:36 |
| 合計ジャッジ時間 | 3,011 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 17 WA * 6 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int main() {
// 1. 入力情報取得.
int N;
cin >> N;
vector<char> n;
queue<char> p1, m1, p2, m2;
for(int i = 0; i < N; i++){
char c;
cin >> c;
if(c == '+') p1.push(c), p2.push(c);
if(c == '-') m1.push(c), m2.push(c);
if(c >= '0' && c <= '9') n.push_back(c);
}
// 2. sort.
sort(n.begin(), n.end());
// 3. 数式作成.
string fMax = "";
// 3-1. 最大値.
for(auto &x : n){
// マイナス追加.
if(fMax.size() > 0 && !m1.empty()){
string s1(1, x);
string s2(1, m1.front());
fMax = s1 + s2 + fMax;
m1.pop();
continue;
}
// プラス追加.
if(fMax.size() > 0 && m1.empty() && !p1.empty()){
char c = p1.front();
string s1(1, x);
string s2(1, p1.front());
fMax = s1 + s2 + fMax;
p1.pop();
continue;
}
// 数字追加.
string s(1, x);
fMax = s + fMax;
}
// cout << "fMax=" << fMax << endl;
// 3-2. 最小値.
string fMin = "";
for(auto &x : n){
// プラス追加.
if(fMin.size() > 0 && !p2.empty()){
char c = p2.front();
string s1(1, x);
string s2(1, p2.front());
fMin += s2;
fMin += s1;
p2.pop();
continue;
}
// マイナス追加.
if(fMin.size() > 0 && p2.empty() && !m2.empty()){
string s1(1, x);
string s2(1, m2.front());
fMin += s2;
fMin += s1;
m2.pop();
continue;
}
// 数字追加.
string s(1, x);
fMin += s;
}
// 一番最後の '-' 以降を, 修正.
// ex. fMin=0+1-2-39 => fMin=0+1-2-93
int last = fMin.rfind("-");
if(last != string::npos){
string rStr = "";
for(int i = last + 1; i < fMin.size(); i++) rStr = fMin[i] + rStr;
for(int i = last + 1; i < fMin.size(); i++) fMin[i] = rStr[i - last - 1];
}
// cout << "fMin=" << fMin << endl;
// 4. 数式を元に計算.
// 4-1. 最大値.
string eos(1, '+');
fMax += eos; // 番兵.
LL aMax = 0, cur = 0;
char bef = '+';
for(int i = 0; i < fMax.size(); i++){
char c = fMax[i];
// 数値の場合.
if(c != '+' && c != '-'){
cur *= 10;
cur += (c - '0');
continue;
}
// 記号の場合.
if(c == '+' || c == '-'){
if(bef == '+') aMax += cur;
if(bef == '-') aMax -= cur;
cur = 0;
bef = c;
}
}
// 4-2. 最小値.
fMin += eos; // 番兵.
LL aMin = 0;
cur = 0;
bef = '+';
for(int i = 0; i < fMin.size(); i++){
char c = fMin[i];
// 数値の場合.
if(c != '+' && c != '-'){
cur *= 10;
cur += (c - '0');
continue;
}
// 記号の場合.
if(c == '+' || c == '-'){
if(bef == '+') aMin += cur;
if(bef == '-') aMin -= cur;
cur = 0;
bef = c;
}
}
// 5. 出力.
// ex.
// [入力値]
// 10
// 2 - 1 8 - 0 + - 3 9
//
// [出力値]
// fMax=98+3-2-1-0 => 98 で良いかどうか???
// fMin=0+1-2-3-98 => -102 で良いかどうか???
cout << aMax << " " << aMin << endl;
return 0;
}
@abcde