Sean has got a Treasure map which shows when and where the dragon balls will appear. some dragon balls will appear in a line at the same time for each period.Since the time you got one of them,the other dragon ball will disappear so he can only and must get one Dragon ball in each period.Digging out one ball he will lose some energy.Sean will lose |x-y| energy when he move from x to y.Suppose Sean has enough time to get any drogan ball he want in each period.We want to know the minimum energy sean will lose to get all period’s dragon ball.
1 3 2 5 2 3 4 1 1 3 1 1 1 3 4 2
8
有m个时期,每个时期有n个龙珠,分别处于不同的位置L[i][j]:i时期 第j个龙珠 所处位置。 每次取到i时期 j龙珠时需要消耗 E[i][j] 个能量。并且还要消耗从上一时期位置x到这个时期龙珠所处位置y 的路程消耗: |x-y| 每一时期必须且仅能取一个球。问m个时期后最少的消耗。
这题直接暴力DP是O(m*n*n);
利用单调队列优化后是O(m*(n+n))
可以利用单调队列的情况就是,上一个状态对这个状态不产生影响,所以可以记录对当前影响的最值
方程式是dp[i][j]=min(dp[i][j],dp[i-1][k]+abs(x[i][j]-x[i-1][k])+val[i][j]),我们把方程式变形,分情况讨论当上一层的点在当前点的左边时记录dp[i][k]-x[i-1][k]的最小值,这样就保证了
记录的值与这一层点状态无关,且因为按横坐标排序,所以只遍历了一遍上一层的点,当上一层的点在当前点的右边时情况类似
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <bitset>
#include <map>
#include <queue>
#include <stack>
#include <vector>
using namespace std;
const int inf = 0x3f3f3f3f;
const int N = 1e5+10;
struct node
{
int x, val, dp;
}p[51][1005];
int cmp(node A,node B)
{
return A.x<B.x;
}
int q[N];
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
int m, n, x;
scanf("%d %d %d", &m, &n, &x);
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
scanf("%d", &p[i][j].x),p[i][j].dp=inf;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d", &p[i][j].val);
}
sort(p[i]+1,p[i]+n+1,cmp);
}
for(int i=1;i<=n;i++) p[1][i].dp=abs(x-p[1][i].x)+p[1][i].val;
int head, tail, k;
for(int i=2;i<=m;i++)
{
head=tail=0,q[0]=-1,k=1;
for(int j=1;j<=n;j++)
{
while(p[i-1][k].x<=p[i][j].x && k<=n)
{
while(head<tail && q[tail-1]>p[i-1][k].dp-p[i-1][k].x) tail--;
q[tail++]=p[i-1][k].dp-p[i-1][k].x;
k++;
}
if(q[head]==-1) continue;
p[i][j].dp=q[head]+p[i][j].val+p[i][j].x;
}
head=tail=0,q[0]=-1,k=n;
for(int j=n;j>=1;j--)
{
while(p[i-1][k].x>=p[i][j].x &&k>=1)
{
while(head<tail && q[tail-1]> p[i-1][k].dp+p[i-1][k].x) tail--;
q[tail++]=p[i-1][k].dp+p[i-1][k].x;
k--;
}
if(q[head]==-1) continue;
p[i][j].dp=min(p[i][j].dp,q[head]+p[i][j].val-p[i][j].x);
}
}
int ans=inf;
for(int i=1;i<=n;i++) ans=min(ans,p[m][i].dp);
cout<<ans<<endl;
}
return 0;
}