結果

問題 No.297 カードの数式
ユーザー furafura
提出日時 2020-05-31 01:59:18
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 379 ms / 1,000 ms
コード長 1,391 bytes
コンパイル時間 3,019 ms
コンパイル使用メモリ 210,088 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-26 17:58:51
合計ジャッジ時間 4,006 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 2 ms
5,376 KB
testcase_03 AC 2 ms
5,376 KB
testcase_04 AC 8 ms
5,376 KB
testcase_05 AC 2 ms
5,376 KB
testcase_06 AC 2 ms
5,376 KB
testcase_07 AC 1 ms
5,376 KB
testcase_08 AC 2 ms
5,376 KB
testcase_09 AC 1 ms
5,376 KB
testcase_10 AC 2 ms
5,376 KB
testcase_11 AC 2 ms
5,376 KB
testcase_12 AC 2 ms
5,376 KB
testcase_13 AC 4 ms
5,376 KB
testcase_14 AC 4 ms
5,376 KB
testcase_15 AC 3 ms
5,376 KB
testcase_16 AC 283 ms
5,376 KB
testcase_17 AC 7 ms
5,376 KB
testcase_18 AC 9 ms
5,376 KB
testcase_19 AC 2 ms
5,376 KB
testcase_20 AC 3 ms
5,376 KB
testcase_21 AC 5 ms
5,376 KB
testcase_22 AC 3 ms
5,376 KB
testcase_23 AC 2 ms
5,376 KB
testcase_24 AC 144 ms
5,376 KB
testcase_25 AC 379 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

#define rep(i,n) for(int i=0;i<(n);i++)

using namespace std;
using lint=long long;

const long long INF=1LL<<61;

map<vector<int>,pair<lint,lint>> memo[15][15];

pair<lint,lint> dfs(vector<int> a,int plus,int minus){
	if(a.empty()) return {-INF,INF};

	if(memo[plus][minus].count(a)>0) return memo[plus][minus][a];

	lint mx=-INF,mn=INF;
	int n=a.size();
	rep(S,1<<n){
		if(S==0 || (plus==0 && minus==0 && S!=(1<<n)-1)) continue;

		vector<int> b,c;
		rep(i,n){
			if(S>>i&1) b.emplace_back(a[i]);
			else       c.emplace_back(a[i]);
		}
		sort(b.begin(),b.end());

		lint tmp_mx=0,tmp_mn=0;
		rep(i,b.size()){
			tmp_mx=10*tmp_mx+b[b.size()-1-i];
			tmp_mn=10*tmp_mn+b[i];
		}

		if(plus==0 && minus==0){
			mx=max(mx,tmp_mx);
			mn=min(mn,tmp_mn);
		}
		else{
			if(plus>0){
				auto t=dfs(c,plus-1,minus);
				mx=max(mx,t.first+tmp_mx);
				mn=min(mn,t.second+tmp_mn);
			}
			if(minus>0){
				auto t=dfs(c,plus,minus-1);
				mx=max(mx,t.first-tmp_mn);
				mn=min(mn,t.second-tmp_mx);
			}
		}
	}
	return memo[plus][minus][a]={mx,mn};
}

int main(){
	int n; scanf("%d",&n);
	vector<int> a;
	int plus=0,minus=0;
	rep(i,n){
		char c; scanf(" %c",&c);
		if(isdigit(c)) a.emplace_back(c-'0');
		else if(c=='+') plus++;
		else            minus++;
	}

	sort(a.begin(),a.end());

	auto ans=dfs(a,plus,minus);
	printf("%lld %lld\n",ans.first,ans.second);

	return 0;
}
0