题目
传送门 to usOJ(只有蒟蒻可进入)
思路
这种题都比较套路了,就是 把可行方案建成一个 “堆” 。
这个堆不一定是二叉,不一定是完满,但是儿子数量比较少。这样我们有如下策略:首先将根丢入优先队列,每次取出队列头,并将其在 “堆” 中的儿子塞入优先队列。
很明显这样是正确的。以大根堆举例。如果 a > b a>b a>b ,那么 a a a 的祖先比 a a a 大,自然就比 b b b 大。在整个过程中,这一条从根到 a a a 的链一定先于 b b b 访问,所以 a a a 比 b b b 先入队列,不会因为队列中的元素不齐全而出错。
回到这个题。用 ⟨ x 1 , x 2 , … , x k ⟩ \lang x_1,x_2,\dots,x_k\rang ⟨x1,x2,…,xk⟩ 表示在第 i i i 组中选择第 x i x_i xi 大的数字。构造父节点 往往很容易。找到最小的 r r r 使得 x r ≠ 1 x_r\ne 1 xr=1 ,那么其父节点就是 ⟨ x 1 , … , x r − 1 , x r − 1 , x r + 1 , … , x n ⟩ \lang x_1,\dots,x_{r-1},x_r-1,x_{r+1},\dots,x_n\rang ⟨x1,…,xr−1,xr−1,xr+1,…,xn⟩ 。想法很好,就是有个问题:有些状态的子节点数量太多!
要知道,复杂度的保证是,如果子节点数量为 c c c ,那么访问 n n n 次最多产生 n c nc nc 个元素。
优化方案是采用 “父亲 − \tt - −兄弟” 表示法。说白了,你把兄弟之间的大小关系搞清楚,然后二者建立父子关系。
在这道题中,这些状态会成为兄弟: ⟨ 2 , 1 , 1 , 1 , … ⟩ , ⟨ 1 , 2 , 1 , 1 … ⟩ , ⟨ 1 , 1 , 2 , 1 , … , ⟩ , ⟨ 1 , 1 , 1 , 2 , … , ⟩ \lang 2,1,1,1,\dots\rang,\lang 1,2,1,1\dots\rang ,\lang 1,1,2,1,\dots,\rang,\lang 1,1,1,2,\dots,\rang ⟨2,1,1,1,…⟩,⟨1,2,1,1…⟩,⟨1,1,2,1,…,⟩,⟨1,1,1,2,…,⟩ ,以此类推。怎么处理?
把组与组之间的顺序调换,按照 a i 0 − a i 1 a_{i0}-a_{i1} ai0−ai1 从小到大排序即可。于是上面的那四个现在变成了一条链,而不是兄弟节点了。
根据父节点,反推子节点就行。你就会惊讶的发现:原来这题水的很呢!
代码
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long int_;
inline int readint(){
int a = 0; char c = getchar(), f = 1;
for(; c<'0'||c>'9'; c=getchar())
if(c == '-') f = -f;
for(; '0'<=c&&c<='9'; c=getchar())
a = (a<<3)+(a<<1)+(c^48);
return a*f;
}
template < typename T >
inline void getMax(T &a,const T &b){
(a < b) ? (a = b) : 0;
}
const int MaxN = 100005;
int n, m; // n 个卡包 求前 m 大
vector< int > v[MaxN]; // 卡包
bool cmp(const vector<int> &a,const vector<int> &b){
return a[0]-a[1] < b[0]-b[1];
}
struct Node{
int id, x; // 第 id 组的第 x 个数
int_ sum; // 目前的求和
bool operator < (const Node &t) const {
return sum < t.sum;
}
};
priority_queue< Node > pq;
void solve(int_ zxy){
Node t, now; t.sum = 0;
t.id = 1, t.x = 0;
for(int i=1; i<=n; ++i)
t.sum += v[i][0];
pq.push(t);
while(!pq.empty()){
t = pq.top(), pq.pop();
printf("%lld ",t.sum+zxy);
if((-- m) == 0) return ;
now = t; // 存档
/* 向前移动一个 */ ;
if(t.id != n && t.x == 1){
t.sum += v[t.id][0];
t.sum -= v[t.id][1];
t.sum -= v[++ t.id][0];
t.sum += v[t.id][1];
pq.push(t), t = now;
}
/* 向前推进一步 */ ;
if(t.id != n && t.x != 0){
t.sum -= v[++ t.id][0];
t.sum += v[t.id][t.x = 1];
pq.push(t), t = now;
}
/* 向深入推一个 */ ;
if(t.x+1u != v[t.id].size()){
t.sum -= v[t.id][t.x];
t.sum += v[t.id][++ t.x];
pq.push(t), t = now;
}
}
}
int main(){
n = readint(), m = readint();
int_ zxy = 0; // 必然的位移
for(int i=1; i<=n; ++i){
int k = readint();
if(k == 1){
zxy += readint();
-- i, -- n;
continue;
}
v[i].clear(); // good habit
for(int j=0; j<k; ++j)
v[i].push_back(readint());
sort(v[i].begin(),v[i].end());
for(int j=0; j<k-j-1; ++j)
swap(v[i][j],v[i][k-j-1]);
}
if(!n){
printf("%lld\n",zxy);
return 0; // 只有这一个
}
sort(v+1,v+n+1,cmp);
solve(zxy);
return 0;
}
后记
大佬的博客或许讲的更清楚。