poj2586贪心

来源:互联网 发布:51单片机综合设计 编辑:程序博客网 时间:2024/05/01 23:15

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 237375 743200000 8496942500000 8000000

Sample Output

11628300612Deficit
大致题意就是每个月只会有正负两种可能的收入,每连续的五个月(1-5,2-6....,8-12)的总收入是负的,问全年的收入有没有可能是正的,是正的就输出全年收入和,负的就输出Deficit。

解法:贪心,要求年收入最大值也就是要收入为负的月份最少,且每个收入为负的月份都要最大化利用,即包括在数量最多的五个月内,首先先把所有月份的收入初始化成正的,然后五个月五个月的遍历,如果收入和是正的就将该月收入改成负的,重要的是进行每五个月的遍历的时候一定要逆序,也就是说优先把后面的月份置为负值,这样可以最大化的利用负值。

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int main(){int s,d;int month[13];while(~scanf("%d %d",&s,&d)){for(int i=1;i<=12;i++)//初始化 {month[i]=s;}int sum=0;for(int i=1;i<=8;i++){for(int j=0;j<5;j++)//求接下来五个月的收入和 {sum+=month[i+j]; } for(int j=i+4;j>=i;j--)//逆序遍历 {  if(sum>0&&month[j]>0)//收入和大于零就将本月份收入改为负,同时更新sum  { month[j]=-1*d; sum=sum-s-d; }} sum=0;}sum=0;for(int i=1;i<=12;i++){sum+=month[i];}if(sum>=0)printf("%d\n",sum);elseprintf("Deficit\n");}return 0;}



0 0
原创粉丝点击