POJ 2823
#define MAXN 1000003
int a[MAXN];
int n,m;
struct node {
int num,t;
}q[MAXN];
int head,rear;
void add(int num,int i) {
while(head <= rear && q[rear].num <= num) rear--;
rear++;
q[rear].num = num;
q[rear].t = i;
}
void addmin(int num,int i) {
while(head <= rear && q[rear].num >= num) rear--;
rear++;
q[rear].num = num;
q[rear].t = i;
}
int get(int i) {
while(head <= rear && q[head].t < i) head ++;
return q[head].num;
}
void init() {
head = rear = 0;
memset(&q,-127,sizeof(struct node));
int i;
for(i = 0;i<n;i++) {
scanf("%d",&a[i]);
}
for(i = 0;i<m;i++) {
addmin(a[i],i);
}
printf("%d",get(0));
for(i = m;i<n;i++) {
addmin(a[i],i);
printf(" %d",get(i-m+1));
}
puts("");
head = rear = 0;
memset(&q,-127,sizeof(struct node));
for(i = 0;i<m;i++) {
add(a[i],i);
}
printf("%d",get(0));
for(i = m;i<n;i++) {
add(a[i],i);
printf(" %d",get(i-m+1));
}
puts("");
}
int main () {
//FOPEN;
while(~scanf("%d%d",&n,&m)) {
init();
}
}
Today we are talking about monotonous DP. I have never understood it carefully before. Today I understand it. monotonous queue is an optimization. It is the most important problem to evaluate a continuous set of data within a certain range, since it is the most valuable optimization in the range, it is widely used. The classic one is the magnificent waltz.
The monotonous queue is really bare, but the Tangle is WA and TLE. Later I found that my problem encountered an error during initialization. initialization should be a minimum value, in this way, the value is successfully assigned during the first comparison!
12 31 3 5 7 -1 -1 -1 -1 7 7 7 712 41 3 5 7 -1 -1 -1 -1 7 7 7 712 4-2000000000 -2 -3 -4 -5 -6 -5 -4 -3 -2 -1 012 32000000000 -2 -3 -4 -5 -6 -5 -4 -3 -2 -1 0
The specific test case is also available in discuss after this question.
However, G ++ still times out!
This monotonous DP is particularly difficult to grasp. It won't happen at all. Why don't you spend a few days on your own!