反悔贪心:在确保能反悔以贴合全局最优解的前提下,选择局部最优解
(理论上来说,这种算法要建出费用流模型才能保证正确性,但是。。)
不好说,上例题:
首先发现每个 坐标小的点会对其上方的一个矩形形成限制,就是不能同时存在点。我们对每个点记录它被限制的代价和。
具体来说,删除自己需要付出 的代价,而保留自己,删除它下面的点需要付出 的代价。
那么对于一个点 来说,删除它下面的点的代价和是多少呢?注意删除一个点 后,要付出 的代价,但 下面的点会因此而不用被删,于是总代价为 。在这里,原来决策 不被删,而现在 改为被删,这就是反悔所在。
对每个点在树状数组上加上 ,扫到一个点时比较 与 即可。
代码如下:
#include <bits/stdc++.h>
#define For(i,a,b) for(int i=a;i<=b;i++)
#define Rev(i,a,b) for(int i=a;i>=b;i--)
#define Fin(file) freopen(file,"r",stdin)
#define Fout(file) freopen(file,"w",stdout)
using namespace std;
const int N=4e5+5;
typedef long long ll;
class FTree{
int n; ll c[N];
int lowbit(int x) { return x&(-x); }
public:
void init(int n0) { n=n0; }
void poke(int p,int x)
{
while(p<=n) { c[p]+=x; p+=lowbit(p); }
}
ll peek(int p)
{
ll res=0;
while(p) { res+=c[p]; p-=lowbit(p); }
return res;
}
};
FTree T;
struct Point{
int x,y,c,w;
bool operator< (const Point& p) const
{
return y<p.y;
}
};
Point pt[N];
int n,m;
pair<int,int> a[N];
set<int> st;
signed main()
{
cin>>n;
For(i,1,n) { cin>>a[i].first; a[i].second=i; }
sort(a+1,a+1+n);
cin>>m;
For(i,1,m){
cin>>pt[i].x>>pt[i].y>>pt[i].c; pt[i].w=0;
}
sort(pt+1,pt+1+m);
For(i,1,n) st.insert(i);
int pa=0;
st.insert(0); st.insert(n+1);
ll ans=0;
T.init(n);
For(i,1,m){
while(pa<n&&a[pa+1].first<pt[i].y) st.erase(a[++pa].second);
auto it=st.lower_bound(pt[i].x);
int r=(*it)-1,l=(*(--it))+1;
ll w=T.peek(pt[i].x),c=pt[i].c;
if(c<w){
ans+=c;
}
else{
ans+=w;
T.poke(l,c-w); T.poke(r+1,-(c-w));
}
}
cout<<ans<<endl;
cerr<<"Time = "<<1.0*clock()/CLOCKS_PER_SEC<<" s\n";
return 0;
}