Codeforces-1183E

題面描述:

A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".

You are given a string ss consisting of nn lowercase Latin letters.

In one move you can take any subsequence tt of the given string and add it to the set SS. The set SS can't contain duplicates. This move costs n|t|n−|t|, where |t||t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).

Your task is to find out the minimum possible total cost to obtain a set SS of size kk or report that it is impossible to do so.

輸入描述:

The first line of the input contains two integers nn and kk (1n,k1001≤n,k≤100) — the length of the string and the size of the set, correspondingly.

The second line of the input contains a string ss consisting of nn lowercase Latin letters.

輸出描述:

Print one integer — if it is impossible to obtain the set SS of size kk, print -1. Otherwise, print the minimum possible total cost to do it.

樣例:

樣例解釋:

In the first example we can generate SS = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in SS is 00 and the cost of the others is 11. So the total cost of SS is 44.

題目大意:給定一個長度爲n的字符串s,要求你在字符串s的基礎上給出k個不同的子序列,每個長度爲t的子序列會花費 n-t,求所有子序列的最小花費和。

解題思路:可以把最原始的字符串當作圖的頂點開始進行BFS操作,用一個SET合集來確認當前字符串是否已經操作過。

AC代碼

#pragma GCC optimize(3)
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<array>
#include<string>
#include<cstring>
#include<cmath>
#include<cassert>
#include<cstdlib>
#include<utility>
#include<iterator>
using namespace std;
#define lowbit(x) x&(-x)
typedef long long ll;

int main()
{
    ios::sync_with_stdio(false);cin.tie(0);
    int n,k;
    string s;
    set<string> st;
    queue<string> q;
    cin>>n>>k;
    cin>>s;
    int ans = 0;
    q.push(s);
    st.insert(s);
    while(!q.empty()&&(int)st.size()<k)
    {
        string ns  =  q.front();
        q.pop();
        for(int i = 0; i<(int)ns.size();i++)
        {
            string ss = ns;
            ss.erase(i,1);
            if(st.count(ss)==0&&(int)(st.size())+1<=k)
            {
                q.push(ss);
                st.insert(ss);
                ans+=(n-(int)ss.size());
            }
        }
    }
    if((int)st.size()<k){
        cout<<-1<<endl;
    }else
    {
        cout<<ans<<endl;
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章