Main topic: First input N (n≤1000), n is an even number, and then enter n integers, n integers and not more than 1,000,000. Two people can only be taken from the two ends at a time, the first person A may use any strategy, the second person B with greedy strategy (left and right number equal to take number). In order to ensure that the first person obtains and the largest premise, the two people take the number and the difference of the maximum value.
Problem solving: Dynamic programming. The breakthrough is that a can take both ends of the number, B can only take the maximum number of two (the same left), and each time a number is taken, can take a number of the interval will be reduced by one. For a, there are two options for each fetch, and if a knows the best and the difference in the less range, then the optimal choice can be made. For B, it is easier to use only greedy selection at a time.
A[i] represents the number of bits I. (0≤i < N)
M[I][J] Indicates the difference between the best and the remainder of I-J. (0≤i≤j < N)
When the interval is odd (i.e. (j-i+1)% 2 = = 1), B selects the number, with greedy strategy:
If A[i] >= a[j], then m[i][j] = m[i+1][j]-a[i].
If a[i] < a[j], then m[i][j] = m[i][j-1]-a[j].
When the interval is even (i.e. (j-i+1)% 2 = = 0), a selects the number, enumerates the two ends, and chooses the best and the difference:
M[I][J] = max (A[i] + m[i+1][j], A[j] + m[i][j-1]).
The code is as follows:
1#include <iostream>2#include <algorithm>3 using namespacestd;4 5 Const intMAXN =1005;6 intM[MAXN][MAXN];//M[i][j] represents the first person's maximum profit for the remainder i-j interval7 //If the interval is odd j-i + 1 is odd, then let the second person according to the greedy algorithm first select8 //If the interval is even j-i + 1 is an even number, let the first person choose according to the best interests first9 intA[MAXN];Ten intN; One A voidInitintN) { - for(inti =0; I < n; i++) { - for(intj =0; J < N; J + +) { theM[I][J] =0; - } - } - } + - intMain () { + intt =0; A while(Cin >> N, n! =0) { att++; - for(inti =0; I < n; i++) { -CIN >>A[i]; - } - -Init (n);//Initialize Matrix in - for(inti =1; I <= N; i++) { to for(intj =0; J < N; J + +) { + intK = j + I-1; - if(k > N-1) Break; the //J-K is the interval around the end * ifI2==1) {//odd interval, the second person chooses first $ if(A[j] >= a[k]) {//large or equal left endpointPanax NotoginsengM[j][k] = m[j +1][K]-A[j]; -}Else{//Small left End theM[J][K] = m[j][k-1] -A[k]; + } A}Else{//even interval, first person chooses first theM[j][k] = max (a[j]+m[j+1][k], a[k]+m[j][k-1]); + } - } $ } $ -cout <<"In game"<< T <<", the greedy strategy might lose by as many as"<< m[0][n-1] <<"points."<<Endl; - } the - return 0;Wuyi}
SOJ 1176, Ends