考虑子任务 2,有一个贪心:我们每次都选择 最大的 个数输出,并把这些 减去 。
为什么这样是对的呢?如果我们挑了 更小的数,那么就有可能让后面几次操作后提前让 ,那么可操作的种类就会减少,有可能就构造不出方案了。
由此,对于一种方案序列 ,把 丢进堆贪心即可求得最后答案。
于是我们转而思考怎样的 是合法的。
考虑霍尔婚配定理:任意取 个 中的元素,设这个集合为 ,则其邻域即为 ,这个数必须大于 。
这个条件即是充要的,然后就可以愉快的 dp 啦。
代码:
#include<bits/stdc++.h>
#define rep(i, j, k) for(int i=(j); i<=(k); ++i)
#define per(i, j, k) for(int i=(j); i>=(k); --i)
#define aprint(a, len) cout<<#a<<"="; rep(i, 0, len-1) cout<<(a)[i]<<' '; cout<<endl
using namespace std;
namespace DEBUG{
template<class T> void _debug(const char *s, T x) {cout<<s<<'='<<x<<endl;}
template<class F, class... Nxt> void _debug(const char *s, F x, Nxt... nxt){
int d=0;
while(*s!=',' || d) d+=*s=='(', d-=*s==')', cout<<*s++;
cout<<'='<<x<<',';
_debug(s+1, nxt...);
}
#define debug(...) _debug(#__VA_ARGS__, __VA_ARGS__)
} using namespace DEBUG;
const int N=1.5e4+3;
using pa=pair<int, int>;
using Bit=bitset<N>;
int n, maxn, a[N], m, b[N], lim[N], cnt[N], sum[N];
vector<Bit> f[N];
Bit pre[N];
vector<int> res;
priority_queue<pa> q;
vector<pa> buc;
void dfs(int i, int j, int k){
if(!i) return;
if(j<f[i-1].size() && f[i-1][j][k]) return dfs(i-1, j, k);
if(f[i][j-1][k-b[i]]){
res.emplace_back(b[i]);
return dfs(i, j-1, k-b[i]);
}
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
cin>>n;
rep(i, 1, n){
cin>>a[i], maxn=max(maxn, a[i]);
++cnt[1], --cnt[a[i]], sum[a[i]]+=a[i];
}
rep(i, 1, maxn) cnt[i]+=cnt[i-1], sum[i]+=sum[i-1], lim[i]=cnt[i]*i+sum[i];
rep(i, maxn+1, lim[maxn]) lim[i]=lim[maxn];
cin>>m;
rep(i, 1, m) cin>>b[i];
reverse(b+1, b+m+1);
f[0].resize(1), f[0][0][0]=1;
rep(i, 1, m) f[i].resize(lim[maxn]/b[i]+1);
pre[0][0]=1;
rep(i, 1, lim[maxn]) pre[i]=pre[i-1], pre[i][i]=1;
rep(i, 1, m){
f[i][0]=f[i-1][0];
rep(j, 1, lim[maxn]/b[i]){
f[i][j]=f[i][j-1]<<b[i];
if(f[i-1].size()>j) f[i][j]|=f[i-1][j];
f[i][j]&=pre[lim[j]];
}
}
bool flag=1;
rep(j, 1, lim[maxn]/b[m])
if(f[m][j][lim[maxn]]){
dfs(m, j, lim[maxn]);
flag=0;
break;
}
if(flag) return cout<<-1, 0;
reverse(res.begin(), res.end());
rep(i, 1, n) q.emplace(a[i], i);
cout<<res.size()<<'\n';
for(auto x:res){
cout<<x<<' ';
rep(_, 1, x){
pa y=q.top(); q.pop();
cout<<y.second<<' ';
if(y.first) buc.emplace_back(pa(y.first-1, y.second));
}
cout<<'\n';
for(auto x:buc) q.emplace(x);
buc.clear();
}
}