CF2174A Needle in a Haystack

思路

首先我们发现:只要从 $t$ 中去掉子串 $s$ 中的字母,其余字母一定不受约束,按照字典序排列。
所以我们枚举去掉 $s$ 中的字母的其他字母,若其字典序大于此时的 $s$ 的还没用的首位,就加入 $s$ 的首位,否则就加入其余字母的首位。
若在去掉 $s$ 中的字母后有某种字母不足 $0$ 个,则显然无法使得 $t$ 有 $s$ 子串,输出Impossible

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<bits/stdc++.h>
#define fir first
#define sec second
#define int long long
#define pii pair<int,int>
#define fep(i,s,e) for(int i=s;i<e;i++)
#define pef(i,s,e) for(int i=s;i>e;i--)
#define rep(i,s,e) for(int i=s;i<=e;i++)
#define per(i,s,e) for(int i=s;i>=e;i--)
namespace FastIO{
template<typename T>inline void read(T &x){
x=0;int f=1;char c=getchar();
for(;!isdigit(c);c=getchar())if(c=='-')f=-1;
for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+(c^48);x*=f;
}
template<typename T,typename...Args>
inline void read(T &x,Args&...args){
read(x);read(args...);
}
template<typename T>void print(T x){
if(x<0)x=-x,putchar('-');
if(x>9)print(x/10);
putchar((x%10)^48);
}
}
using namespace std;
using namespace FastIO;
const int N=4e5+7;
int T;
string s,t;
map<char,int>cnt,use;
signed main(){
read(T);
while(T--){
cnt.clear();
use.clear();
cin>>s>>t;
fep(i,0,t.size()){
cnt[t[i]]++;
}
fep(i,0,s.size()){
use[s[i]]++;
}
int flag=1;
fep(i,0,26){
char c='a'+i;
cnt[c]-=use[c];
if(cnt[c]<0){
flag=0;
}
}
if(flag==0){
puts("Impossible");
continue;
}
string tmp="",ans="";
fep(i,0,26){
char c='a'+i;
rep(j,1,cnt[c]){
tmp+=c;
}
}
int t=0;
fep(i,0,tmp.size()){
while(tmp[i]>=s[t]&&t<s.size()){
ans+=s[t];t++;
}
ans+=tmp[i];
}
while(t<s.size()){
ans+=s[t];
t++;
}
fep(i,0,ans.size()){
putchar(ans[i]);
}
puts("");
}
}