BOJ 14888:挿入演算子-C++
挿入演算子
コード#コード# #include <cstdio>
#include <vector>
#include <queue>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <set>
#include <deque>
#include <numeric>
#define ll long long
#define ull unsigned long long
using namespace std;
// 1004 ~ 1022
int N, ansB=-1e9, ansS=1e9;
vector<int> v;
int cnt[4];
void func(int depth, int tot)
{
if(depth == N){
ansB = max(ansB, tot);
ansS = min(ansS, tot);
return;
}
for(int j=0;j<4;j++)
{
int prev = tot;
if(cnt[j] == 0) continue;
if(j == 0) tot += v[depth];
else if(j == 1) tot -= v[depth];
else if(j == 2) tot *= v[depth];
else if(j == 3) tot /= v[depth];
cnt[j]--;
func(depth+1, tot);
cnt[j]++;
tot = prev;
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> N;
for(int i=0;i<N;i++)
{
int a;
cin >> a;
v.push_back(a);
}
for(int i=0;i<4;i++)
cin >> cnt[i]; // + , -, x, /
func(1,v[0]);
cout << ansB << '\n';
cout << ansS << '\n';
return 0;
}
#include <cstdio>
#include <vector>
#include <queue>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <set>
#include <deque>
#include <numeric>
#define ll long long
#define ull unsigned long long
using namespace std;
// 1004 ~ 1022
int N, ansB=-1e9, ansS=1e9;
vector<int> v;
int cnt[4];
void func(int depth, int tot)
{
if(depth == N){
ansB = max(ansB, tot);
ansS = min(ansS, tot);
return;
}
for(int j=0;j<4;j++)
{
int prev = tot;
if(cnt[j] == 0) continue;
if(j == 0) tot += v[depth];
else if(j == 1) tot -= v[depth];
else if(j == 2) tot *= v[depth];
else if(j == 3) tot /= v[depth];
cnt[j]--;
func(depth+1, tot);
cnt[j]++;
tot = prev;
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> N;
for(int i=0;i<N;i++)
{
int a;
cin >> a;
v.push_back(a);
}
for(int i=0;i<4;i++)
cin >> cnt[i]; // + , -, x, /
func(1,v[0]);
cout << ansB << '\n';
cout << ansS << '\n';
return 0;
}
:
백트래킹
を使用して、演算子に従って모든 경우의 수
を수행
Reference
この問題について(BOJ 14888:挿入演算子-C++), 我々は、より多くの情報をここで見つけました https://velog.io/@neity16/BOJ-14888-연산자-끼워넣기-Cテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol