Knapsack problem poj 3264

来源:互联网 发布:mac cad中文版 编辑:程序博客网 时间:2024/05/16 17:40



Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536KTotal Submissions: 31136 Accepted: 14678Case Time Limit: 2000MS

Description

For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.

Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.

Input

Line 1: Two space-separated integers, N and Q
Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i 
Lines N+2..N+Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.

Output

Lines 1..Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

Sample Input

6 31734251 54 62 2

Sample Output

630

/* 背包问题简洁版 ,改一下刷新的方向就是完全背包或者是不完全背包,建议对照原版看,不明白打印二维数组*/#include<iostream>#include<stdio.h>using namespace std;int mm[ 12881 ]={0};int w[3403];int v[3403];int main(){int n,m,i,j;scanf("%d%d",&n,&m);for(i=0;i<n;i++)scanf("%d%d",&w[i],&v[i]);    //mm[i][j] 表示选择在[i..n-1]容量为j情况下的最大值,但事实上用一维存就够了          for( i=n-1;i>=0;i-- )      {//for( j=m;j>=w[i];j-- ) //从这个方向刷新是上轮的,每个宝贝at most once                                              //for( j=w[i];j<=m;j++ )  //从这个方向刷新的是本轮的 ,每个宝贝选择不限次数 for( j=m;j>=w[i];j-- ) //从这个方向刷新是上轮的,每个宝贝at most oncemm[j]=max( mm[j] , mm[ j-w[ i ] ] +v[i] );    }printf("%d\n",mm[ m ]);system("pause");return 0;}


1 0
原创粉丝点击