codeforces 128B - String

本文介绍了一个关于字符串处理的问题,即如何找出一个给定字符串的所有子串,并按字典序排序后找到第k个子串。文章提供了一段AC代码实现,通过优先队列来高效地解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

One day in the IT lesson Anna and Maria learned about the lexicographic order.

String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≤ i ≤ min(|x|, |y|)), thatxi < yi, and for any j (1 ≤ j < ixj = yj. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languages​​.

The teacher gave Anna and Maria homework. She gave them a string of length n. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string "aab": "a", "a", "aa", "ab", "aab", "b"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the k-th string from the list. Help Anna and Maria do the homework.

Input

The first line contains a non-empty string that only consists of small Latin letters ("a"-"z"), whose length does not exceed 105. The second line contains the only integer k (1 ≤ k ≤ 105).

Output

Print the string Anna and Maria need — the k-th (in the lexicographical order) substring of the given string. If the total number of substrings is less than k, print a string saying "No such line." (without the quotes).

AC代码:

 

#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <queue>
using namespace std;
char c[100001];
int cn;
string s[100001];
int ed[100001];
struct Cmp{
    bool operator()(int a, int b){
        return s[a] > s[b];
    }
};
typedef priority_queue<int, vector<int>, Cmp> pq;
pq pri;
int main() {
    while ( scanf("%s", c) != EOF ){
        cn = strlen(c);
        pq().swap(pri);//将队列清空
        for (int ci = 0; ci < cn; ci++){
            s[ci] = c[ci];
            ed[ci] = ci;
            pri.push(ci);
		}
        int k;
        scanf("%d", &k);
        for (int ki = 0; ki < k; ki++) {
            if ( pri.empty() ) {
                puts("No such line.");
                break;
            }
            int t = pri.top();
            pri.pop();
            if ( ki+1 == k ) puts(s[t].c_str() );
            ed[t]++;
            if ( ed[t] != cn ){
                s[t].push_back(c[ed[t]]);
                pri.push(t);
            }
        }
    }
	return 0;
}
 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值