570 div 3 E

传送门:https://codeforces.com/contest/1183/problem/E

题面描述:

  给你一个长度为n的字符串,你可以从中删掉字母(也可以不删),将这样得到的一个字符串放进一个集合s中,让你求一个容量大小为k的集合的最小花费,整个集合的花费是由集合内所有字符串花费的和,每个字符串的花费是 |n-该字符串的长度|。如果不可能组成大小为k的集合,输出-1,否则,输出最小花费。

思路:

  这个题的思路有点意思,是字符串bfs,概括来说,就是先从删一个字符开始,将原串删掉一个字符的所有字串都用一个set存起来,,接下来枚举删掉两个字符的串,即在删掉一个字母的字串的基础上再删掉一个字符,直到队列为空或者set的大小达到k结束bfs。

代码:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n,k;
    cin >> n >> k;
    string s;
    cin >> s;
    int ans = 0;
    queue<string> q;
    set<string> st;
    q.push(s);
    st.insert(s);
    while(!q.empty()&&int(st.size()<k))
    {
        string v = q.front();
        q.pop();
        for(int i = 0; i<int(v.size()); ++i)
        {
            string nv = v;
            nv.erase(i,1);
            if(!st.count(nv) && int(st.size())+1 <=k)
            {
                q.push(nv);
                st.insert(nv);
                ans += n - nv.size();
            }
        }
    }
    if(int(st.size()<k)) cout << -1 <<endl;
    else cout << ans << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/baihualiaoluan/p/11219155.html