1. 程式人生 > 實用技巧 >牛客網Mask Allocation

牛客網Mask Allocation

題目描述 :

Nowadays, the Kingdom of Dreamgrid is suffering from a national pandemic.

Fortunately,president Baobao is working effectively with the Center for Disease Control (CDC) and they are trying their best to make everything under control.

President Baobao has received n×mn \times mn×m medical masks from his friend Reku, an extremely rich billionaire.

As the chief of the CDC, you are required to allocate these masks properly.

There are 2 kinds of hospitals in the Kingdom of Dreamgrid, n senior hospitals for critically ill patients and m mobile cabin hospitals for patients with mild symptoms.

Before allocating them to hospitals, you have to pack them into boxes.

Please note that boxes must not be opened in order to prevent contamination and you only know these boxes will be allocated to either senior hospitals or mobile cabin hospitals.

That is to say, there should be a way of dividing masks boxes into m groups of n masks, and a way of dividinginto n groups of m masks.

You want the number of boxes to be minimal and please also provide a lexicographically greatest sequence of the numbers of masks in boxes. We say a sequence a is lexicographically greater than another b of the same length if there exists an integer i, such that

    • aj=bja_j = b_jaj=bj, for all j < i; and
    • ai>bia_i > b_iai>bi.

首先判斷n是否大於m,若大於,則使得n<m。

由於要求字典序最大,裝口罩最多的盒子不超過n。

醫院數量為n的時候,需要給每個醫院安排m個口罩,至多給每個醫院(m/n)個(向下取整(這很重要!)),每個盒子裝著n個,總的就是(m/n)×n個盒子,每個醫院還要再拿m%n個口罩。
這時候我們考慮醫院數量為m的情況,此時需要給每個醫院分配n個口罩,那顯然已經有(m/n)×n個醫院滿足條件了,還有m%n個醫院沒拿到。

這樣,我們就把問題轉化成了n’= m % n,m’= n的子問題,不斷迴圈即可。

上程式碼(靈魂!)

#include<bits/stdc++.h>
using namespace std;
int t,n,m,ans,a[100010];
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        ans=0;
        while(n>0)
        {
            if(n<m) swap(n,m);
            for(int i=1; i<=m; i++) a[++ans]=m;
            n-=m;
        }
        printf("%d",ans);
        printf("\n");
        for(int i=1; i<=ans; i++) printf("%d ",a[i]);
        printf("\n");
    }
}
View Code