第二題大模擬真的有點折磨了
第一題
給出m種飲料,每種飲料只有一杯,接下來有n個客人,每個客人有兩種想喝的飲料,請問最多能滿足多少位客人。
資料範圍比較小n = 20,所以直接暴力求解
#include<bits/stdc++.h>
using namespace std;
int main() {
int n,m;
cin >> n >> m;
int res = 0;
vector<int> ind(m + 1, 0);
vector<vector<int>> nums;
for (int i = 0; i < n; i++) {
int a,b;
cin >> a >> b;
nums.push_back(vector<int>{a,b});
}
function<void(int,int)> dfs = [&] (int pox, int now) {
if (pox == n) {
res = max(res, now);
return;
}
if (ind[nums[pox][0]] == 0 && ind[nums[pox][1]] == 0) {
ind[nums[pox][0]] = 1;
ind[nums[pox][1]] = 1;
dfs(pox + 1, now + 1);
ind[nums[pox][0]] = 0;
ind[nums[pox][1]] = 0;
}
dfs(pox + 1, now);
};
dfs(0, 0);
cout << res;
return 0;
}
第二題
給出T個方程,允許在每個方程中新增至多一位數字,詢問每個方程是否成立。
給定的方程中只有“+*="和數字三種符號。T至多為10,每個方程的長度至多為1000。
以下解法只透過82% Runtime Error
- 列舉對應的插入位置
- 根據等號拆分開
- 模擬進行表示式的計算
#include <bits/stdc++.h>
using namespace std;
int cacu(string s) {
int n = s.length();
stack<int> st;
int pox = 0;
int left = 0;
while (pox < n) {
while (pox < n && s[pox] != '+' && s[pox] != '*') {
pox++;
}
long long tmp = stoi(s.substr(left, pox - left));
left = pox + 1;
while (pox < n && s[pox] == '*') {
pox++;
while (pox < n && s[pox] != '+' && s[pox] != '*') {
pox++;
}
int tmp2 = stoi(s.substr(left, pox - left));
left = pox + 1;
tmp = tmp * tmp2;
}
st.push(tmp);
pox++;
}
long long res = 0;
while (!st.empty()) {
res += st.top();
st.pop();
}
return res;
}
bool scheck(string s) {
int epox = 0;
while (s[epox] != '=') {
epox++;
}
string s1 = s.substr(0, epox);
string s2 = s.substr(epox + 1);
if (cacu(s1) == cacu(s2)) return true;
else return false;
}
const char chars[]{'0','1','2','3','4','5','6','7','8','9'};
int main() {
int T;
cin >> T;
for (int p = 0; p < T; p++) {
string s;
cin >> s;
scheck(s);
int len = s.length();
if (scheck(s)) {
cout << "Yes" <<endl;
continue;
}
bool flag = false;
for (int i = 0; i < 10 && (!flag); i++) {
for (int j = 0; j <= len && (!flag);j++) {
string tmp1 = s.substr(0, j);
string tmp2 = s.substr(j);
string s1 = tmp1 + chars[i] + tmp2;
if (scheck(s1)) flag = true;
}
}
if (flag) cout << "Yes" <<endl;
else cout << "No" <<endl;
}
return 0;
}