George and Accommodation 【CodeForces - 467A】
George and Accommodation問題解析
題目
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.
Time limit | Memory limit | Source | Tag | Editoria |
---|---|---|---|---|
1000 ms | 262144 kB | Codeforces Round #267 (Div. 2) | simplementation *800 | Announcement |
Input
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.
Output
Print a single integer — the number of rooms where George and Alex can move in.
Example
input | output |
---|---|
3 1 1 2 2 3 3 | 0 |
3 1 10 0 10 10 10 | 2 |
問題連結:CodeForces - 467A
問提描述
喬治和艾利克斯要住進同一個宿舍,輸入資料第一行為宿舍總數n,而後會有n行的輸入,每一行有兩個資料分別是宿舍中已經入住的人數和宿舍可以入住的人數,得到所有資料後計算有幾個宿舍可供兩個人入住。
問題分析
首先獲得有幾個宿舍的資料,然後新建一個長度為n*2的陣列用於儲存宿舍人數情況,最後利用一個計數器記錄那些宿舍的空位大於等於2,輸出計數器的值即可。
AC通過的C++語言程式程式碼如下:
#include<iostream>
using namespace std;
int main()
{
int n;
int counter = 0;
cin >> n;
int *dom = new int[n*2];
for (int i = 0; i < n * 2; i++)
cin >> dom[i];
for (int i = 0; i < n * 2; i += 2)
if (dom[i + 1] - dom[i] >= 2)
counter++;
cout << counter;
}
程式碼分析
一開始聲明瞭兩個變數,n是宿舍總數,counter是計數器,然後動態建立陣列dom來儲存人數情況
int n; //宿舍總數
int counter = 0; //計數器
cin >> n; //獲得宿舍總數
int *dom = new int[n*2]; //根據宿舍總數建立陣列
然後就是輸入宿舍的人數情況
for (int i = 0; i < n * 2; i++)
cin >> dom[i];
然後就會得到一個儲存著:已有,總數,已有,總數…的陣列
之後就計算有幾個宿舍有兩個以上空位
for (int i = 0; i < n * 2; i += 2)
if (dom[i + 1] - dom[i] >= 2)
counter++;
這裡利用之前輸入資料的格式,每兩個資料為一組進行一次迴圈,遇到可入住數減去已入住數大於2的,計數器就加1,最後輸出計數器的值即可。