BZOJ 1560 火星藏宝图(DP)
很容易想到直接排序然后DP。令dp[i]为到达i点的最大收益,则有dp[i]=max(dp[j]-(xi-xj)^2-(yi-yj)^2+v[i]).(j<=i,xj<=xi,yj<=yi)。
时间复杂度为O(n^2).显然超时。
考虑到转移的特性。假设在计算dp[i]的时候,j,k在同一列且xj<xk。那么一定有j通过k转移到i比直接从j转移更优。证明很容易。
所以我们只需要枚举小于等于i的列,取当前列的最大纵坐标转移即可。
时间复杂度O(nm).
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# include <cstdio> # include <cstring> # include <cstdlib> # include <iostream> # include <vector> # include <queue> # include <stack> # include <map> # include <set> # include <cmath> # include <algorithm> using namespace std; # define lowbit(x) ((x)&(-x)) # define pi 3.1415926535 # define eps 1e-9 # define MOD 100000007 # define INF 1000000000 # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define bug puts("H"); # define lch p<<1,l,mid # define rch p<<1|1,mid+1,r # define mp make_pair # define pb push_back typedef pair<int,int> PII; typedef vector<int> VI; # pragma comment(linker, "/STACK:1024000000,1024000000") typedef long long LL; int Scan() { int res=0, flag=0; char ch; if((ch=getchar())=='-') flag=1; else if(ch>='0'&&ch<='9') res=ch-'0'; while((ch=getchar())>='0'&&ch<='9') res=res*10+(ch-'0'); return flag?-res:res; } void Out(int a) { if(a<0) {putchar('-'); a=-a;} if(a>=10) Out(a/10); putchar(a%10+'0'); } const int N=200005; //Code begin... struct Node{int x, y, v;}node[N]; int vis[1005], dp[N]; bool comp(Node a, Node b){ if (a.y==b.y) return a.x<b.x; return a.y<b.y; } int main () { int n, m; n=Scan(); m=Scan(); FOR(i,1,n) node[i].x=Scan(), node[i].y=Scan(), node[i].v=Scan(), dp[i]=-INF; sort(node+1,node+n+1,comp); dp[1]=node[1].v; vis[1]=1; FOR(i,2,n) { for (int j=node[i].x; j>=1; --j) { if (!vis[j]) continue; int k=vis[j]; dp[i]=max(dp[i],dp[k]-(node[i].x-node[k].x)*(node[i].x-node[k].x)-(node[i].y-node[k].y)*(node[i].y-node[k].y)); } dp[i]+=node[i].v; vis[node[i].x]=i; } printf("%d\n",dp[n]); return 0; }