您的位置:首页 > 其它

ural 1648. Yachts 栈

2011-05-23 09:04 162 查看
//其实想到用逆向+栈就很简单了,,比赛的时候想到逆,,但没深想,陷入了思维牛角尖里

//至于为什么逆向呢? 很显然,当从后向前遍历的时候,这一个月的游艇需求是否能够满足只与它前面的月份库存量有关,,我只需把不足游艇量存起来,然后继续向月份小的推进,以希望之前的月份可以能够弥补这次的不足.

//至于花费最少,i.e.弥补时候要弥补之后与弥补月最近的月,这样不会比弥补其他月份更劣,这便想到了栈实现...

/*
ID:1192432
PROG: castle
LANG: C++
*/
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <map>
#include <vector>
#include <memory.h>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const long long MAX=20005,INF=1<<30;
struct Stack{
    long long mon,rest;
};
long long n,d,a[MAX],top;
Stack s[MAX];
int main()
{
#ifndef ONLINE_JUDGE
    freopen("i.txt", "r", stdin);
#endif
    long long all,cost,can;
    Stack t;
    while(cin>>n>>d){
        all=cost=0;
        top=-1;

        for(long long i=1;i<=n;i++){
            cin>>a[i];
        }
        for(long long i=n;i>=1;i--){
            if(d<a[i]){
                all+=d;
                t.rest=a[i]-d;
                t.mon=i;
                s[++top]=t;
            }
            else{//if(d>a[i])
                all+=a[i];
                //cout<<"ALL: "<<all<<endl;
                can=d-a[i];
                while(top!=-1&&can>0){
                    //cout<<"I: "<<i<<" "<<can<<endl;
                    Stack &item=s[top];
                    if(item.rest>can){
                        item.rest-=can;
                        all+=can;
                        //cout<<"in ALL: "<<all<<endl;
                        cost+=can*(item.mon-i);
                        can=0;
                    }
                    else{
                        can-=item.rest;
                        all+=item.rest;
                        cost+=item.rest*(item.mon-i);
                        item.rest=0;
                        --top;
                    }
                }
            }
        }
        cout<<all<<" "<<cost<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: