递归与分治法 | Poj2586

题目:http://poj.org/problem?id=2586

Description

Accounting for Computer Machinists (ACM) has sufferred from the Y2K bug and lost some vital data for preparing annual report for MS Inc. 

All what they remember is that MS Inc. posted a surplus or a deficit each month of 1999 and each month when MS Inc. posted surplus, the amount of surplus was s and each month when MS Inc. posted deficit, the deficit was d. They do not remember which or how many months posted surplus or deficit. MS Inc., unlike other companies, posts their earnings for each consecutive 5 months during a year. ACM knows that each of these 8 postings reported a deficit but they do not know how much. The chief accountant is almost sure that MS Inc. was about to post surplus for the entire year of 1999. Almost but not quite. 

Write a program, which decides whether MS Inc. suffered a deficit during 1999, or if a surplus for 1999 was possible, what is the maximum amount of surplus that they can post.

Input

Input is a sequence of lines, each containing two positive integers s and d.

Output

For each line of input, output one line containing either a single integer giving the amount of surplus for the entire year, or output Deficit if it is impossible.

Sample Input

59 237
375 743
200000 849694
2500000 8000000

Sample Output

116
28
300612
Deficit

基本思路:

这个题目本身是一种穷举算法,每个月两种可能性(盈利或赤字),12月一共2的12次方种可能性。于是题目的要求是要尽量盈利,因此我们无需穷举所以的可能性,而只需要用递归的方式,尽可能的让每个月盈利。针对其中某个月,我们首先认为当月盈利;当当月盈利导致整年的收支不符合要求时,我们再认为当月亏损。

代码:

#include <iostream>
#include <math.h>
using namespace std;

int* income;
int s,d;

int Cal5Month(int Month)
{
int sum = 0;
for(int i = Month – 4; i <= Month; i++)
{
sum += income[i];
}
return sum;
}

bool SetIncome(int Month)
{
if(Month == 11)
{
income[Month] = s;
if(Cal5Month(Month) >= 0)
{
income[Month] = d;
if(Cal5Month(Month) >= 0)
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
else if(Month >= 4)
{
income[Month] = s;
if(Cal5Month(Month) < 0 && SetIncome(Month+1))
{
return true;
}
else
{
income[Month] = d;
if(Cal5Month(Month) < 0 && SetIncome(Month+1))
{
return true;
}
else
{
return false;
}
}
}
else
{
income[Month] = s;
if(SetIncome(Month+1))
{
return true;
}
else
{
income[Month] = d;
return SetIncome(Month+1);
}
}
}

int main()
{
income = new int[12];
while(cin>>s>>d)
{
d *= -1;
if(SetIncome(0))
{
int sum = 0;
for(int i = 0; i < 12; i++)
{
sum += income[i];
}
if(sum < 0)
{
cout<<“Deficit”<<endl;
}
else
{
cout<<sum<<endl;
}

}
else
{
cout<<“Deficit”<<endl;
}
}

return 0;
}

    原文作者:递归与分治算法
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/9751867
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞