【PAT-A】1014. Waiting in Line (30)

这份相当于自己写了一个优先队列所以多了很多可能不必要的计算量,如果熟悉模板库的还是用模板库会好很多……

最烦的一个测试点是用户是否被服务取决于开始服务的时间而不是结束服务的时间(其实这个点讲道理还是比较符合正常逻辑的

结构如下图
这里写图片描述
如果能用优先队列还是用优先队列吧orz


/*
@author Birdy 18.2.18 
whether a customer is served depends on the time of being served
看了朋友写的优先队列……还是用STL代码清楚一点……符合正常的逻辑……(其实思路差不多……我写这个把我绕进去好几次……)
*/

#include <iostream>
using namespace std;
int N, M, K, Q;

// find the min in the queue, return index
// if same return the one with the smallest number

int findmin(const int* queue_all)
{
    int min = queue_all[0], index = 0;
    for (int i = 0; i < N * M; i++)
    {
        if (queue_all[i] < min)
        {
            index = i;
            min = queue_all[i];
        }
    }
    return index;
}

// this two functions to standardise the output time
void print2(int time)
{
    if (time < 10) 
    {
        cout << '0';
    }
    cout << time;
}

void transfer(int time)
{
    if (time < 0)
    {
        cout << "Sorry" << endl;
        return;
    }
    print2(time / 60 + 8);
    cout << ':';
    print2(time % 60);
    cout << endl;


}

int main(void)
{
    cin >> N >> M >> K >> Q;
    int *time = new int[K];
    int *queue_all = new int[N * M];
    int time_temp, index_temp;
    for (int i = 0; i < N * M; i++)
    {
        //initialize
        queue_all[i] = 0;
    }
    for (int i = 0; i < K; i++)
    {
        cin >> time_temp;

        if (i < M * N) // put the M*N customers in the line to initialize the queue
        {
            int m = (i / N) + (i % N) * M;

            for (int j = m; j < M * (m / M) + M; j++)
            {
                queue_all[j] += time_temp;
            }
            if (queue_all[m] - time_temp < 60 * 9)
                time[i] = queue_all[m];
            else
                time[i] = -1;

        }
        else // add the customer in the line which has a customer about to finish & with mini index 
        {
            index_temp = findmin(queue_all);
            int time_max = queue_all[index_temp];
            for (int j = M * (index_temp / M); j < M * (index_temp / M) + M; j++)
            {
                if (time_max < queue_all[j]) 
                {
                    time_max = queue_all[j];
                }
            }
            queue_all[index_temp] = time_max + time_temp;

            if (queue_all[index_temp] - time_temp < 60 * 9)
                time[i] = queue_all[index_temp];
            else
                time[i] = -1;
        }
    }

    int index;
    for (int i = 0; i < Q; i++)
    {
        cin >> index;
        transfer(time[index-1]);// input start from 1;  not same as index
    }

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/birdy_/article/details/79372512