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 = ababc
, a
, bab
and ababc
are substrings of s, while ac
, z
and an empty string are not. Also, we say that substrings are different when they are different as strings.
Let X=x1x2…xn and Y=y1y2…ym 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 xj≠yj.
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
aba 4
Sample Output 1
b
s has five substrings: a
, b
, ab
, ba
and aba
. Among them, we should print the fourth smallest one, b
. Note that we do not count a
twice.
Sample Input 2
atcoderandatcodeer 5
Sample Output 2
andat
Sample Input 3
z 1
Sample Output 3
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;
}