CF-1020-D. Flower Boy · znzryb
## 思路讲解
preA配合sufA,寻找最优插值位置
## AC代码
::: 源代码
```cpp
// Problem: D. Flower Boy
// Contest: Codeforces - Codeforces Round 1020 (Div. 3)
// URL: https://codeforces.com/contest/2106/problem/D
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// by znzryb
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
#define all(x) x.begin(),x.end()
#define CLR(i,a) memset(i,a,sizeof(i))
#define fi first
#define se second
#define pb push_back
#define SZ(a) ((int) a.size())
#define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
#define ROF(i, a, b) for (int i = (a); i >= (b); --i)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef __int128 i128;
typedef pair<ll,ll> pll;
typedef array<ll,3> arr;
typedef double DB;
typedef pair<DB,DB> pdd;
typedef pair<ll,bool> plb;
constexpr ll MAXN=static_cast<ll>(2e5)+10,INF=static_cast<ll>(5e18)+3;
constexpr ll mod=static_cast<ll>(1e9)+7;
ll N,M,T,A[MAXN],B[MAXN],sufA[MAXN],preA[MAXN];
inline void solve(){
cin>>N>>M;
FOR(i,0,N+5){
sufA[i]=0;
preA[i]=0;
}
FOR(i,1,N){
cin>>A[i];
}
deque<ll> q;
FOR(i,1,M){
cin>>B[i];
q.pb(B[i]);
}
ll idx=0;
FOR(i,1,N){
if(q.empty()) break;
if(A[i]>=q.front()) q.pop_front(),++idx;
preA[i]=idx;
}
if(q.empty()){
cout<<0<<"\n";
return;
}
q.clear();
FOR(i,1,M){
q.pb(B[i]);
}
idx=0;
ROF(i,N,1){
if(A[i]>=q.back()){
q.pop_back();
++idx;
}
sufA[i]=idx;
}
#ifdef LOCAL
FOR(i,1,N){
cerr<<sufA[i]<<" ";
}
cerr<<"\n";
FOR(i,1,N){
cerr<<preA[i]<<" ";
}
cerr<<"\n\n";
#endif
ll ans=INF;
bool haveAns=false;
FOR(i,0,N){
if(sufA[i+1]+preA[i]==M-1){
ans=min(ans,B[preA[i]+1]);
haveAns=true;
}
}
if(!haveAns){
cout<<-1<<"\n";
return;
}
cout<<ans<<"\n";
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>T;
while(T--){
solve();
}
// solve();
return 0;
}
/*
1
4 4
1 1 3 3
1 2 3 6
AC https://codeforces.com/contest/2106/submission/317145066
*/
```
:::
## 心路历程(WA,TLE,MLE……)