找个例题:
http://codeforces.com/contest/1328/problem/B
B. K-th Beautiful String
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
For the given integer n (n>2) let’s write down all the strings of length n which contain n−2 letters ‘a’ and two letters ‘b’ in lexicographical (alphabetical) order.
Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1≤i≤n), that si<ti, and for any j (1≤j<i) sj=tj. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.
For example, if n=5 the strings are (the order does matter):
aaabb
aabab
aabba
abaab
ababa
abbaa
baaab
baaba
babaa
bbaaa
It is easy to show that such a list of strings will contain exactly n⋅(n−1)2 strings.
You are given n (n>2) and k (1≤k≤n⋅(n−1)2). Print the k-th string from the list.
Input
The input contains one or more test cases.
The first line contains one integer t (1≤t≤104) — the number of test cases in the test. Then t test cases follow.
Each test case is written on the the separate line containing two integers n and k (3≤n≤105,1≤k≤min(2⋅109,n⋅(n−1)2).
The sum of values n over all test cases in the test doesn’t exceed 105.
Output
For each test case print the k-th string from the list of all described above strings of length n. Strings in the list are sorted lexicographically (alphabetically).
Example
inputCopy
7
5 1
5 2
5 8
5 10
3 1
3 2
20 100
outputCopy
aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa
题目大意:
input: t,n,k
t 组数据, 字符串长度 n , 输出第k 个字符串
字符串从尾部bb开始排列,主要是确定b的位置,设 pre, lat指向b,
i , j 分别为 pre,lat 的左移单位数
初始 pre = n - 2 ,lat = n -1
题目转换为,寻找 i ,j 与 k 的关系
然后列个表看看:
i 0 1 1 2 2 2 3 3 3 3
j 0 0 1 0 1 2 0 1 2 3
s 1 2 3 4 (这一行表示每一个i 对应 排列种数)
k 1 2 3 4 5 6 7 8 9 10
i 与 s : s = i + 1
s 与 k: s(s+1)/2 (确定每一个边界对应)
j 与 k: k(n-1) + j + 1 = k;
通过第二个条件确定边界就基本解决了;
如下:
#include <iostream>
using namespace std;
typedef long long ll;
void get_pre(int& pre,int& lat,const int n,const ll k)
{
int i = 0, j = 0;
for(int u = 0;u<n;++u)
{
int s = u + 1;
if((ll)s * (s + 1)/ 2 >= k)
{
i = u ;
break;
}
}
//
ll before= (ll)i * (i + 1) / 2;
j = k - before - 1;
//
pre -= i;
lat -= j;
}
//
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
int t, n;
ll k;
while (cin >> t)
{
while (t--)
{
cin >> n >> k;
int pre = n - 2, lat = n - 1;
get_pre(pre, lat, n, k);
for (int i = 0; i < n; ++i)
{
if (i == pre || i == lat)
cout << 'b';·
else
cout << 'a';
}
cout << '\n';
}
}
return 0;
}
好像也类似 112123.。。。
对
1121231234----1 2 3 4 5 6 7 8 9 10类: 寻找第k个数
1
1 2
1 2 3
....
1 2 3 4 5... n
第n行有 n个数,
1 2 3 4 5…等差数列 Sn = n(n+1)/2
通过遍历找到所在行
if(Sn>k) break; //此时得到大一个的n
所在行 即:n -1
则所在列:k - S(n-2)
所在列即为该数字。