P7302 [NOI1998] 免费的馅饼 题解
- \(upd \> on \> 26.10.5\):修 \(\LaTeX\)
\(solve\)
- 首先,们可以将题目转化为类似此题:Fire(有区别但是差不多但是不能这么解),考虑 \(dp\)
- 转移方程:\(dp_i=\max dp_j+v_i\)
- 此时应满足:\(2 \times (t_i−t_j) ≥ \mid p_i−p_j\mid\)
- 容易发现需要两层循环,时间复杂度为 \(O(n^2)\),而 \(n=10^5\),超时
- 考虑用数据结构优化
- 对于上述满足 \(dp\) 条件的不等式,我们进行化简得出:
- 当 \(p_i≥p_j\) 时,有:\(p_j - 2 \times t_j ≥ p_i - 2 \times t_i\)
- 当 \(p_i<p_j\) 时,有:\(p_i + 2 \times t_i ≥ p_j + 2 \times t_j\)
- 对于上述两个不等式,一个用于排序,一个用于算 \(a_{i}.x\)
\(code\)
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int w,n;
int c[maxn];
int dp[maxn];
int sum[maxn];
int ans;
struct node
{
int t,p,v,x;
}a[maxn];
bool cmp (node nd1,node nd2){return nd1.p-2*nd1.t>=nd2.p-2*nd2.t;}
int lowbit(int x){return (x&(-x));}
void add(int w,int x)
{
while(w<=n)
{
c[w]=max(c[w],x);
w+=lowbit(w);
}
}
int query(int w)
{
int res=0;
while(w)
{
res=max(res,c[w]);
w-=lowbit(w);
}
return res;
}
int main()
{
cin >> w >> n;
for (int i=1;i<=n;i++)
{
cin >> a[i].t >> a[i].p >> a[i].v;
sum[i]=2*a[i].t+a[i].p;
}
sort (sum+1,sum+1+n);
for (int i=1;i<=n;i++)
{
a[i].x=lower_bound(sum+1,sum+1+n,2*a[i].t+a[i].p)-sum;
}
sort(a+1,a+1+n,cmp);
for (int i=1;i<=n;i++)
{
dp[i]=query(a[i].x)+a[i].v;
add(a[i].x,dp[i]);
ans = max(ans,dp[i]);
}
cout << ans << endl;
return 0;
}
$\frak{msjing}$

浙公网安备 33010602011771号