题解:AT_abc416_c [ABC416C] Concat (X-th)

· · 题解

题意

给你 n 个字符串和一个正整数 k 和 x,要求连接字符串数组中的 k 个字符串(可以重复),问连接后第 x 小的字符串

思路

看了一眼数据范围,n \le 10 , k \le 5,立刻就想到是深搜,时间复杂度 O\left ( n^k \right ),可以接受。

那么就是枚举每个位置中能填的 n 个字符串,填完后记录答案,最后排序输出即可。

代码

#include <bits/stdc++.h>

using namespace std;

#define endl '\n'

#define TRACE 1
#define tcout TRACE && cout

#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);

#define int long long

const int P = 998244353;
const int Base = 3221225477;
const int INF = 0x3f3f3f3f3f3f3f3f;

const int N = 1e2 + 10, M = 2e6 + 10;

int n, k;

string s[N]; 

vector<string> a;

string b[N];

void dfs(int x)
{
    if(x == k + 1)//跳出条件 
    {
        string t = "";//记录连接后的字符串 
        for(int i = 1; i <= k; i++)
        {
            t += b[i];
        }
        a.push_back(t);//记录到总答案中 
        return;
    }
    for(int i = 1; i <= n; i++)//枚举每个可以填的字符串 
    {
        b[x] = s[i];
        dfs(x + 1);
        b[x] = "";//回溯 
    }
}

signed main() 
{ 
    int x;
    cin >> n >> k >> x;
    for(int i = 1; i <= n; i++)
    {
        cin >> s[i];
    }
    dfs(1);
    sort(a.begin(), a.end());//排序 
    cout << a[x - 1];//输出第x小 
    return 0;
}