Atcoder Beginner Contest097 C题

C题题面:

C - K-th Substring


Time limit : 2sec / Memory limit : 1024MB

Score : 300 points

Problem Statement

You are given a string s. Among the different substrings of s, print the K-th lexicographically smallest one.

A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = ababcabab and ababc are substrings of s, while acz and an empty string are not. Also, we say that substrings are different when they are different as strings.

Let X=x1x2xn and Y=y1y2ym be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or xj>yj where j is the smallest integer such that xjyj.

Constraints

  • 1  |s|  5000
  • s consists of lowercase English letters.
  • 1  K  5
  • s has at least K different substrings.

Partial Score

  • 200 points will be awarded as a partial score for passing the test set satisfying |s|  50.

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.


Sample Input 1

Copy
aba
4

Sample Output 1

Copy
b

s has five substrings: ababba and aba. Among them, we should print the fourth smallest one, b. Note that we do not count a twice.


Sample Input 2

Copy
atcoderandatcodeer
5

Sample Output 2

Copy
andat

Sample Input 3

Copy
z
1

Sample Output 3

Copy
z


详解:

200分做法:

#include <bits/stdc++.h>
using namespace std;
string s[10000];
int ans;
void gas(string x)
{  
if(x.size()==0)return;  
else
{  
for(int i=0;i<x.size();i++)  
{  
for(int j=1;j<x.size()+1;j++)  
{
ans++;
if (i+j<=x.size())
s[ans]=x.substr(i,j);
}  
}       
}  



int main()
{
ios::sync_with_stdio(false);
string str;
int g;
cin>>str>>g;
gas(str);
int i,j;
for(i=0;i<ans-1;i++)
for(j=0;j<ans-1-i;j++)
{
const char *x=s[j].data(),*y=s[j+1].data();
if(strcmp(x,y)>0)
{
swap(s[j],s[j+1]);
}
}
ans=0;
for (i=1;i<=1000000;i++)
{
if (s[i]!=s[i-1])
{
ans++;
}
if (ans==g)
{
cout<<s[i]<<endl;
return 0;
}
}
return 0;

}

这种做法从第25个点起回RE,只能拿200分

满分做法:

#include <bits/stdc++.h>
using namespace std;
set<string> strs;
bool compare(string s1, string s2) {
    for (int i=0;i<min(s1.size(), s2.size());i++) {
        if (s1[i] > s2[i]) {
            return true;
        } else if (s1[i] < s2[i]) {
            return false;
        }
    }
    return s1.size() > s2.size();
}
 
string ith(int x) {
    auto itr = strs.begin();
    for (int i=0;i<x-1;i++)itr++;
    return *itr;
}
 
int main () {
    string s;
    int k;
    cin >> s >> k;
    for (int i=0;i<s.size();i++) {
        if (strs.size() > k) {
            string t = ith(k);
            if (compare(s.substr(i), t)) continue;
        }
        for (int j=0;i+j<s.size();j++) {
            strs.insert(s.substr(i, j+1));
        }
    }
    cout << ith(k) << endl;
}

猜你喜欢

转载自blog.csdn.net/fu_xuantong/article/details/80295458