Here's the problem WCM faces. He gets a list of how many buses are available from each company over each of the next n days. But he can only contact one of the companies in any given day. On day i, there are ai(ai > 0) buses available if he contacts Company A and there are bi(bi > 0) buses available if he contacts Company B. He also has the ability to change from one company to the other, but doing this takes one day in which no buses are available.
So, given a sequence of n days, a plan is specified by a choice of A, B, or "change" for each day, with the constraint that choice A and B cannot appear in consecutive days. For example, if he contacts Company A in day i, and he wants to switch to company B, then his choice for day i+1 must be "change", and then his choice for day i+2 can be B. The value of a plan is the total number of buses that he manages to arrange for the students of UESTC over the n days: so it's the sum of ai over all days in which the buses are available from Company A, plus the sum of bi over all days in which the buses are available from Company B.
The problem: Given the values of a1, a2, a3 … an and b1, b2, b3 … bn, find a plan of the maximum value(Such a plan is called optimal). Note that your plan can start with either of the company A or B in day 1.
Example: Suppose n = 4 and the values of ai and bi are given by the following table.
Day 1 Day 2 Day 3 Day 4 A 11 2 2 9 B 4 1 21 23 Then the plan of the maximum value would be to choose A for day 1, then "change" for day 2, and then B for day 3 and 4. The value of this plan would be 11+0+21+23=55.Facing this problem, WCM feels despaired. He asks you for help to solve this problem. Give an efficient algorithm that takes values for a1, a2 … an and b1, b2 … bn and returns the value of an optimal plan.
#include <iostream>#define MAX 1000003using namespace std;int a[MAX][2],t,n;int GetMax(int a,int b) { if(a>b) return a; else return b; }int main() { int i,j; cin>>t; while(t--) { scanf("%d",&n); for(i=1;i<=2;i++) for(j=1;j<=n;j++) scanf("%d",&a[j][i]); for(j=n-1;j>=1;j--) for(i=2;i>=1;i--) { if(i==2) a[j][2]=GetMax(a[j+1][1],a[j+1][2]+a[j][2]); if(i==1) a[j][1]=GetMax(a[j+1][2],a[j+1][1]+a[j][1]); } int MM=-1; if(a[1][1]>MM) MM=a[1][1]; if(a[1][2]>MM) MM=a[1][2]; printf("%d\n",MM); } return 0; }
转载于:https://www.cnblogs.com/forever4444/archive/2009/05/15/1457831.html
相关资源:数据结构—成绩单生成器