Monotonically queued dp poj 2823

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.