前面两道阅读理解直接跳过。
思路
数据范围不大,可设一个哈希表存储的所有情况,询问时直接在表中查找即可。
代码
#include<iostream>
#include<unordered_map>
using namespace std;
#define int long long
const int N = 114;
int a[N], b[N], c[N];
unordered_map<int,bool> mp;
signed main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n, m, l, q;
cin >> n;
for(int i = 1; i <= n; i++) cin >> a[i];
cin >> m;
for(int i = 1; i <= m; i++) cin >> b[i];
cin >> l;
for(int i = 1; i <= l; i++) cin >> c[i];
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
for(int k = 1; k <= l ;k++) mp[a[i] + b[j] + c[k]] = true;
cin >> q;
for(int i = 1; i <= q; i++){
int x;
cin >> x;
cout << (mp.count(x)? "Yes": "No") << endl;
}
return 0;
}
D - String Bags
思路
dfs+优化。设表示搜到第个背包,字符串长度为的最少选择数,如果当前次数比它还要大,就不用再搜索下去。
代码
#include<iostream>
#include<cstring>
using namespace std;
const int N=210, M=21, INF=0x3f3f3f3f;
int n, ans=INF, a[N], f[N][N];
string t, s[N][M];
void dfs(int x, int sum, string k){
if(x > n){
if(k == t) ans = min(ans, sum);
return;
}
if(sum >= ans || sum >= f[x][k.size()]) return;
f[x][k.size()] = sum;
for(int i = 1; i <= a[x]; i++){
string p = k + s[x][i];
if(p.size() <= t.size() && p == t.substr(0, p.size())) dfs(x + 1, sum + 1, p);
}
dfs(x + 1, sum, k);
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin >> t >> n;
for(int i = 1; i <= n; i++){
cin >> a[i];
for(int j = 1; j <= a[i]; j++) cin >> s[i][j];
}
memset(f, 0x3f, sizeof f);
dfs(1, 0, "");
if(ans == INF) cout << -1 << endl;
else cout << ans << endl;
return 0;
}
E - Insert or Erase
思路
使用链表解决,为了方便,可以用。
但是链表的查找是的,我们还要设一个map,键为列表中的数,值为对应项的迭代器。
注意list的插入是在给定迭代器的前面插入。
代码
#include <iostream>
#include <list>
#include <unordered_map>
#include <iterator>
using namespace std;
typedef list<int>::iterator Iter;
list<int> w;
unordered_map<int,Iter> mp;
int main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n, q;
cin >> n;
for(int i = 1; i <= n; i++){
int x;
cin >> x;
w.push_back(x);
auto it = prev(w.end());
mp[x] = it;
}
cin >> q;
while(q--){
int op, x, y;
cin >> op >> x;
if(op==1){
cin >> y;
auto it=mp[x];
mp[y]=w.insert(++it, y);
}else{
auto it = mp[x];
w.erase(it);
mp.erase(x);
}
}
for(int x: w) cout << x << " ";
return 0;
}