题解:P16981 [NWERC 2017] 安装应用 / Installing Apps

· · 题解

其他题解竟然没有反贪做法?来一发。

首先考虑邻项交换。

$c-s_{i+1}<\max(s_i,d_i)$。 变形一下,得到 $\max(s_{i+1},d_{i+1})+s_i\leq c < s_{i+1}+\max(s_i,d_i)$。 也就是 $s_i-\max(s_i,d_i)<s_{i+1}-\max(s_{i+1},d_{i+1})$。 直接按 $s_i-\max(s_i,d_i)$ 排序。 顺序有了之后就很自然了。直接反贪。 能拿就拿。否则从队列里选一个 $s_i$ 最大的,看看反悔优不优,能不能反悔,做一些判断之后,如果更优,就替换。 时间复杂度 $\mathcal O(n\log n)$。不知道为什么 $n$ 要开 $500$,$c$ 要开 $10000$。 ```cpp #include<bits/stdc++.h> using namespace std; /* */ struct FSI{ template<typename T> FSI& operator >> (T &res){ res=0;T f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();} while (isdigit(ch)){res=res*10+ch-'0';ch=getchar();} res*=f; return *this; } }scan; typedef pair<int,int> pii; const int N=510; int n,c,i,x,ans,id; priority_queue<pii> q; bool vis[N]; struct Node{ int d,s,id; }a[N]; bool cmp(Node x,Node y){return x.s-max(x.d,x.s)<y.s-max(y.d,y.s);} int main() { scan>>n>>c; for (i=1;i<=n;i++) scan>>a[i].d>>a[i].s,a[i].id=i; sort(a+1,a+n+1,cmp); for (i=1;i<=n;i++) { if (c>=max(a[i].d,a[i].s)) { ans++; c-=a[i].s; q.push({a[i].s,i}); vis[i]=true; } else { if (q.empty()) continue; x=q.top().first; id=q.top().second; if (x<a[i].s) continue; if (c+x<max(a[i].d,a[i].s)) continue; q.pop(); c=c+x-a[i].s; vis[i]=true; vis[id]=false; q.push({a[i].s,i}); } } printf("%d\n",ans); for (i=1;i<=n;i++) { if (vis[i]) printf("%d ",a[i].id); } return 0; } ```