动态规划初级练习(二):BadNeighbors

时间:2024-09-14 18:36:08

Problem Statement

    

The old song declares "Go ahead and hate your neighbor", and the residents of Onetinville have taken those words to heart. Every resident hates his next-door neighbors on both sides. Nobody is willing to live farther away from the town's well than his neighbors, so the town has been arranged in a big circle around the well. Unfortunately, the town's well is in disrepair and needs to be restored. You have been hired to collect donations for the Save Our Well fund.

Each of the town's residents is willing to donate a certain amount, as specified in the int[] donations, which is listed in clockwise order around the well. However, nobody is willing to contribute to a fund to which his neighbor has also contributed. Next-door neighbors are always listed consecutively indonations, except that the first and last entries in donations are also for next-door neighbors. You must calculate and return the maximum amount of donations that can be collected.

 

Definition

    
Class: BadNeighbors
Method: maxDonations
Parameters: int[]
Returns: int
Method signature: int maxDonations(int[] donations)
(be sure your method is public)
    
 
 

Constraints

- donations contains between 2 and 40 elements, inclusive.
- Each element in donations is between 1 and 1000, inclusive.
 

Examples

0)  
    
 { 10, 3, 2, 5, 7, 8 }
Returns: 19
The maximum donation is 19, achieved by 10+2+7. It would be better to take 10+5+8 except that the 10 and 8 donations are from neighbors.
1)  
    
{ 11, 15 }
Returns: 15
 
2)  
    
{ 7, 7, 7, 7, 7, 7, 7 }
Returns: 21

题目中要求是 一个环中的某些数的和最大,这些数要满足的条件是,不能是相邻的,又因为是一个环,所以首尾两个数也认为是相邻的。这样的话,不妨认为测试数据给出的数组下标是从0~i,第一次先处理A[0]~A[i-1],再处理一次A[1]~A[i],各得出一个最大的,两者较大的即是要求的。处理过程本可以写成一个函数,但是写完懒得改了,就这样吧。

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <set>
#include <list>
#include <cctype>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define REP(i,j,k) for(int i = j ; i < k ; ++i)
#define MAXV (1000)
#define INF (0x6FFFFFFF)
using namespace std;
class BadNeighbors
{
public:
int maxDonations(vector <int> donations)
{
int ans=;
int dp[];
bool flag;
memset(dp,,sizeof dp);
if(donations.size()==) return ;
if(donations.size()==) return donations[];
if(donations.size()==) return max(donations[],donations[]);
REP(i,,donations.size())
{
flag=true;
dp[i]=donations[i];
REP(j,,i-)
{
ans=max(dp[j]+donations[i],ans);
flag=false;
}
if(!flag)
dp[i]=ans;
}
int ret=;
memset(dp,,sizeof dp);
dp[]=donations[];
REP(i,,donations.size()-)
{
dp[i]=donations[i];
flag=true;
REP(j,,i-)
{
ret=max(dp[j]+donations[i],ret);
flag=false;
}
if(!flag)
dp[i]=ret;
}
return max(ans,ret);
}
};
int main()
{
//freopen("in.txt","r",stdin);
int _x[]= { , };
vector<int> x(_x,_x+sizeof(_x)/sizeof(_x[]));
BadNeighbors b;
printf("%d\n",b.maxDonations(x));
return ;
}