UVa 10440 - Ferry Loading II

問題:

一個渡口,有一艘渡船,運汽車到對面,一次能運n輛車,到達對面要t分鐘,返回要t分鐘,一共來m輛車。

給出m個數據,是到達渡口的時間。求最短把全部汽車運到對面的最短時間是多少,次數是多少(時間從0算)。

思路:貪心。

考慮三種情況(也可以說是兩種)

一:n>m.最短時間爲最後一輛車到達渡口的時間+t,次數爲1;

二:n<=m,m恰好整除n。

三:n<=m,m除以n有餘數。

詳細思路代碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;

#define MAXN 1500

int Max(int a,int b){
    if (a>b)
        return a;
    else
        return b;
}

class Ferry{
    private:
        int n;
        int m;
        int t;
        int cars[MAXN];
    public:
        void process();
};

void Ferry::process(){
    int cases;//測試樣例個數
    int ansTime,ansNum;//結果時間,次數


    cin >>cases;
    while(cases--){
        ansTime = 0;
        ansNum = 0;
        cin>>n>>t>>m;
        for(int i = 0;i < m;i++){
            cin>>cars[i];
        }
        
        if(n > m){//來的車輛比每次能運的還要少
            ansTime = cars[m-1] + t;
            ansNum = 1;
        }
        else if(m % n == 0){
            for(int i = n - 1;i < m;i += n){
                ansTime = Max(ansTime,cars[i]);/*比較渡船每次返回(起始也算)渡口的時間和車輛來到渡口的時間,哪個最晚選哪個*/
                ansTime += 2 * t;
            }
            ansTime = ansTime - t;//最後一次不必返航
            ansNum = m/n;
        }
        else{
            int remainder;//求出總車輛和一次能運車輛的餘數
            remainder = m%n;
            ansTime = cars[remainder - 1]+2*t;//先運餘數數目的車輛
            for(int i = remainder + n - 1;i < m;i = i + n){/*剩下就是每次裝滿的情況*/
                ansTime = Max(ansTime ,cars[i] );
                ansTime += 2 * t;
            }
            ansTime -=  t;
            ansNum = m/n + 1;
        }

        cout<<ansTime<<" "<<ansNum<<endl;
    }
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen("D:\\acm.txt","r",stdin);
    #endif // ONLINE_JUDGE
    Ferry ferry;
    ferry.process();
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章