THPTTD_109 - Tìm số thứ N

Xem dạng PDF

Gửi bài giải

Điểm: 10,00 (OI)
Giới hạn thời gian: 1.0s
Giới hạn bộ nhớ: 256M
Input: FindN.inp
Output: FindN.out

Tác giả:
Dạng bài
Ngôn ngữ cho phép
C, C#, C++, Go, Java, JavaScript, Kotlin, Pascal, Perl, PHP, Python, Ruby, Rust, Scratch, Swift

Trong trường hợp đề bài hiển thị không chính xác, bạn có thể tải đề bài tại đây: Đề bài


Bình luận

Hãy đọc nội quy trước khi bình luận.



  • 4
    lephuochauhungvuong  đã bình luận lúc 11, Tháng 3, 2025, 7:53
    #include <iostream>
    #include <queue>
    #include <vector>
    #include <algorithm>
    #include <fstream> // Thư viện để làm việc với file
    
    using namespace std;
    
    // Hàm tìm số thứ N trong dãy
    vector<string> findNthNumbers(const vector<int>& testCases) {
        // Tìm giá trị N lớn nhất trong các test case
        int maxN = *max_element(testCases.begin(), testCases.end());
    
        // Hàng đợi để sinh dãy số
        queue<string> q;
        q.push("4");
        q.push("7");
    
        // Vector lưu dãy số theo thứ tự
        vector<string> result;
    
        // Sinh dãy số cho đến khi đủ maxN phần tử
        while ((int)result.size() < maxN) {
            string current = q.front();
            q.pop();
            result.push_back(current);
            q.push(current + "4");
            q.push(current + "7");
        }
    
        // Tạo kết quả tương ứng cho mỗi test case
        vector<string> output;
        for (int n : testCases) {
            output.push_back(result[n - 1]);
        }
    
        return output;
    }
    
    int main() {
        // Mở tệp đầu vào và đầu ra
        ifstream inputFile("FindN.inp");
        ofstream outputFile("FindN.out");
    
        // Đọc số lượng test case từ tệp
        int T;
        inputFile >> T;
    
        vector<int> testCases(T);
        for (int i = 0; i < T; ++i) {
            inputFile >> testCases[i];
        }
    
        // Tìm kết quả
        vector<string> results = findNthNumbers(testCases);
    
        // Ghi kết quả ra tệp
        for (const string& res : results) {
            outputFile << res << endl;
        }
    
        // Đóng tệp
        inputFile.close();
        outputFile.close();
    
        return 0;
    }