练习cf978C. Letters

题目如下
C. Letters
time limit per test4 seconds
memory limit per test256 megabytes
There are 𝑛 dormitories in Berland State University, they are numbered with integers from 1 to 𝑛. Each dormitory consists of rooms, there are 𝑎𝑖 rooms in 𝑖-th dormitory. The rooms in 𝑖-th dormitory are numbered from 1 to 𝑎𝑖.

A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all 𝑛 dormitories is written on an envelope. In this case, assume that all the rooms are numbered from 1 to 𝑎1+𝑎2+⋯+𝑎𝑛 and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.

For example, in case 𝑛=2, 𝑎1=3 and 𝑎2=5 an envelope can have any integer from 1 to 8 written on it. If the number 7 is written on an envelope, it means that the letter should be delivered to the room number 4 of the second dormitory.

For each of 𝑚 letters by the room number among all 𝑛 dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.

Input
The first line contains two integers 𝑛 and 𝑚 (1≤𝑛,𝑚≤2⋅105) — the number of dormitories and the number of letters.

The second line contains a sequence 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤1010), where 𝑎𝑖 equals to the number of rooms in the 𝑖-th dormitory. The third line contains a sequence 𝑏1,𝑏2,…,𝑏𝑚 (1≤𝑏𝑗≤𝑎1+𝑎2+⋯+𝑎𝑛), where 𝑏𝑗 equals to the room number (among all rooms of all dormitories) for the 𝑗-th letter. All 𝑏𝑗 are given in increasing order.

Output
Print 𝑚 lines. For each letter print two integers 𝑓 and 𝑘 — the dormitory number 𝑓 (1≤𝑓≤𝑛) and the room number 𝑘 in this dormitory (1≤𝑘≤𝑎𝑓) to deliver the letter.
题目大意
现有m封信对应m个房间,共有n个宿舍,但每个信封上只有这n个宿舍中所有房间一起排序后的编号,从第一个宿舍的第一个房间开始,一直到最后一个宿舍的最后一个房间。
现在需要找出每封信对应的宿舍和房间号并输出。

题目分析
现有宿舍数m,和每个宿舍的房间数,并且m封信按照信封上的编码排好,那么只要从第一个宿舍开始的前n个宿舍的总房间数记录下,从后往前排排查;

点击查看代码
for(int i = 1; i <= n; i++){
        cin >> l[i];
        pre[i] = pre[i - 1] + l[i];
    }
    int dorm = 1;
    for(int i = 0; i < m; i++){
        long long num;
        cin >> num;
        while(num > pre[dorm]){
            dorm++;
        }
对应房间号就等于编号减去本寝室前的寝室的总的房间数即可。
点击查看代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(){
    int n, m;
    cin >> n >> m;
    vector<long long> l(n + 1), pre(n + 1);
    pre[0] = 0;
    for(int i = 1; i <= n; i++){
        cin >> l[i];
        pre[i] = pre[i - 1] + l[i];
    }
    int dorm = 1;
    for(int i = 0; i < m; i++){
        long long num;
        cin >> num;
        while(num > pre[dorm]){
            dorm++;
        }
        long long door = num - pre[dorm - 1];
        printf("%d %lld\n", dorm, door);
    }

    return 0;
}

posted @ 2025-07-19 20:41  sirro1uta  阅读(43)  评论(0)    收藏  举报