【題解】CPE 一顆星選集:17. The Hotel with Infinite Rooms

題目

incoming group has one more member than previous
n members stays for n days
Input: S (1~1000, initial size of the group), D (1~10^15, find D-th day group size)
Example: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

UVa 連結
ZeroJudge 連結

解法一:數學公式

1 + 2 + 3 + … + n = n * (n + 1) / 2

#include <iostream>
#define ll long long
using namespace std;

int main(){
    int S;
    ll D;
    while(cin >> S >> D){
        ll n = 1;
        while((n*(n+1)/2) - ((S-1)*S/2) < D){
            n++;
        }
        cout << n << '\n';
    }
}

解法二:模擬

#include <iostream>
#define ll long long
using namespace std;

int main(){
    int S;
    ll D;
    while(cin >> S >> D){
        int now = S;
        while(D > 0){
            D -= now;
            if(D > 0) now++;
        }
        cout << now << '\n';
    }
}
👉 回到:【CPE大學程式能力檢定】目錄
發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *