Codeforces 467A George and Accommodation 喬治與住處

難易度 : 800

英文原文如下

George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.

George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living in it and the room can accommodate qi people in total (pi ≤ qi). Your task is to count how many rooms has free place for both George and Alex.

中文翻譯

George 最近進入了 BSUCP ( Berland 州立酷工程師大學 )。George 有一個朋友 Alex 也進入了這間大學,現在他們要搬進宿舍。

George 跟 Alex 希望可以住在同一個房間。整個宿舍共有 n 個房間,而目前第 i 個房間共有 pi 個人住在裡面,而且整個房間最多可以容納 qi 個人 (pi ≤ qi)。你的任務是要去確認有多少間房間有足夠的空間讓 George 跟 Alex 一起搬進去。

輸入

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of rooms.

The i-th of the next n lines contains two integers pi and qi (0 ≤ pi ≤ qi ≤ 100) — the number of people who already live in the i-th room and the room’s capacity.

第一行包含了一個整數 n (1 ≤ n ≤ 100) — 房間的數量

接下來  n 列中,第 i 列包含了兩個整數 pi 跟 qi (0 ≤ pi ≤ qi ≤ 100) — 分別代表了已經入住的人數以及房間最多可以容納幾個人。

輸出

Print a single integer — the number of rooms where George and Alex can move in.

印出一個整數 — 有多少個房間是 George 跟 Alex 可以入住的。

範例

輸入3
1 1
2 2
3 3
輸出0

每一個房間都住滿人了

輸入3
1 10
0 10
10 10
輸出2

第一個房間還有9個位置,第二個房間沒人入住,還有10個位置

第三個房間已經住滿了,所以答案是 「2」間


解題思路

在我們的解答中,就是要迴圈拜訪每一行輸入並判斷剩餘空位是否大於等於2個 ( George 跟 Alex )。

C#解決方案

方案1

int n = int.Parse(Console.ReadLine());  //total count of rooms 

int res = 0;

for(int i = 0; i<n ; i++)
{
    string[] arr  = Console.ReadLine().Split(' '); //split by space
    int alreadyUsed = int.Parse(arr[0]);
    int capacity = int.Parse(arr[1]);
    
    if(capacity-alreadyUsed >= 2){
        res+=1;
    }
}

Console.WriteLine(res);

Java解決方案

方案1

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine()); //total count of rooms 
        int res = 0;

        for (int i = 0; i < n; i++) 
        {
            String[] arr = scanner.nextLine().split(" ");
            int alreadyUsed = Integer.parseInt(arr[0]);
            int capacity = Integer.parseInt(arr[1]);
            
            if(capacity-alreadyUsed >= 2){
                res+=1;
            }
        }

        System.out.println(res);
    }
}

結論

題目中出現了10人一間的宿舍,好像比較少聽過這麼大間的呢!! 感覺很有趣,但就怕遇上習慣不好的室友呢~

🧡如果文章有幫上你的忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Problem – 467A – Codeforces

一些其他的Codeforces文章

發佈留言

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