AtCoder Beginner Contest 344

前面两道阅读理解直接跳过。

思路

数据范围不大,可设一个哈希表存储A_i+B_j+C_k的所有情况,询问时直接在表中查找即可。

代码

#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+优化。设f_{i,j}表示搜到第i个背包,字符串长度为j的最少选择数,如果当前次数比它还要大,就不用再搜索下去。

代码

#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

思路

使用链表解决,为了方便,可以用\texttt{std::list}

但是链表的查找是O(n)的,我们还要设一个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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值