Thứ Ba, 28 tháng 7, 2026

Một số bài tập C _C++ NC 2026P32

 Bài 140. Tìm số lớn nhất và số nhỏ nhất trong xâu, nếu có số 0 đứng trước thì xóa đi. Xâu có độ dài không quá 1e5 .

File input cb140.txt    06057bggff009999vv606rf

File output Kqcb140.txt  606   9999

Gợi ý code:

#include <iostream>

#include <string>

#include <fstream>

#include <cctype>

using namespace std;

int main(int argc, char** argv) {

           cout<<"Chuong trinh cn140 \n";

           ifstream fd("cb140.txt");

           if(!fd.is_open()){

                     cerr<<"Khong the mo file cb140.txt";

                     return 0;

           }

           string s,x;

           while(fd>>x){

                     s+=x;

           }

           if(s.empty()){cerr<<"khong co data input";

           return 0;

           }

           int si=0, maxx=-1e9, minn=1e9;

           bool cn=false;

           for(char c:s){

                     if(c>='0'&&c<='9') {

                     si=si*10+(c-48);

                     cn=true;}

                     else if(cn){

                     if (si>maxx) maxx=si;

                     if(si<minn) minn=si;

                     si=0;

                     cn=false;

                     }}

           if(cn){

                     if (si>maxx) maxx=si;

                     if(si<minn) minn=si;

                     cn=false;

                     }

           ofstream fo("Kqcb140.txt");

           cout<<"Gia tri lon nhat la: "<<maxx<<"\n";

           fo<<"Gia tri lon nhat la: "<<maxx<<"\n";

           cout<<"Gia tri nho nhat la: "<<minn<<"\n";

           fo<<"Gia tri nho nhat la: "<<minn<<"\n";

           fd.close();fo.close();

           return 0;

}

///////////////////////////////////

Cách 2:

#include <iostream>

#include <string>

#include <fstream>

#include <cctype>

using namespace std;

 

int main() {

    ifstream fd("cb140.txt");

    if (!fd.is_open()) {

        cerr << "Khong the mo file cb140.txt";

        return 0;

    }

 

    string s, x;

    while (fd >> x) s += x;

    fd.close();

 

    if (s.empty()) {

        cerr << "Khong co data input";

        return 0;

    }

 

    int maxx = -1, minn = 1e9;

    string num = "";

 

    for (char c : s) {

        if (isdigit(c)) {

            num += c;

        } else {

            if (!num.empty()) {

                // Xóa số 0 ở đầu

                num.erase(0, num.find_first_not_of('0'));

                if (num.empty()) num = "0";

 

                int val = stoi(num);

                if (val > maxx) maxx = val;

                if (val < minn) minn = val;

                num.clear();

            }

        }

    }

 

    // Xử lý số cuối cùng nếu chuỗi kết thúc bằng số

    if (!num.empty()) {

        num.erase(0, num.find_first_not_of('0'));

        if (num.empty()) num = "0";

        int val = stoi(num);

        if (val > maxx) maxx = val;

        if (val < minn) minn = val;

    }

 

    ofstream fo("Kqcb140.txt");

    fo << minn << "   " << maxx;

    fo.close();

 

    cout << "So nho nhat: " << minn << "\n";

    cout << "So lon nhat: " << maxx << "\n";

 

    return 0;

}

/////////////////////////////////////

Cách 3:

#include <bits/stdc++.h>

using namespace std;

 string s, maxs, mins, x ;

  bool bigger(string a, string b){

        if(a.size()==b.size()) return(a>b);

        return (a.size()> b.size());

  }

int main(){

freopen("cb140.txt","r",stdin);

freopen("Kqcb140.txt","w",stdout);

    cin>>s;

    for(int i=0; i<=s.size(); i++){

            if(s[i]>='0'&& s[i]<='9') x+=s[i];

             else {

                    if(x.size()>0){

                      while(x.size()>1 && x[0]=='0')

                            x.erase(0,1);

                      if(bigger(x,maxs)||maxs=="") maxs =x;

                      if(!bigger(x,mins)||mins=="") mins=x;

                      x="";

}

}

}

cout << mins<< endl <<maxs;

return 0;

}

Chú ý:

  • string có thể rỗng ("") hoặc chứa khoảng trắng (" ").
  • char không thể rỗng, nhưng có thể là ' ' hoặc '\0'.

Ví dụ minh họa:

string a = "";   // chuỗi rỗng

string b = " ";  // chuỗi có 1 khoảng trắng

char c = ' ';    // ký tự khoảng trắng

char d = '\0';   // ký tự null (thường dùng để kết thúc chuỗi C-style)

///////////// Ai memory help

Võ Nhật Trường Nc+ My Ai Love27.07.2026

///////////////////

Bài 141. Một mật thư chứa mật mã bí ẩn được tạo ra là một xâu kí tự chỉ gồm các chữ số và các kí tự in thường. Mật mã bí ẩn là số lượng các số nguyên phân biệt xuất hiện trong thư. Ví dụ: với mật thư 00023dff23ddd1sd23vgg09gf chứa 3 số nguyên phân biệt 23, 1, 9 nên mật mã là 3, độ dài của xâu <=1000 gồm các chữ số và các kí tự in thường, hoa. Em hãy viết chương trình tìm mật mã bí mật nhé.

File input cb141.txt   VD: Abc123abc2de3d1 00023dff23ddd1sd23vgg09gf

File output Kqcb141.txt  Mat ma bi mat la: 7

Gợi ý code:

#include <iostream>

#include <fstream>

#include <vector>

#include <string>

#include <unordered_map>

using namespace std;

 

int main(int argc, char** argv){

    ifstream fin("cb141.txt");

    if(!fin.is_open()) {

        cerr << "Khong the mo file cb141.txt\n";

        return 0;

    }

 

    vector<long long> vo;

    unordered_map<long long,int> mv;

    string s, si;

    while(fin >> si) {

        s += si;

    }

    fin.close();

 

    if(s.empty()) {

        cerr << "Khong co gia tri hop le trong file\n";

        return 0;

    }

 

    long long m = 0;

    bool cn = false;

    for(char c : s){

        if(c >= '0' && c <= '9'){

            cn = true;

            m = m*10 + (c - '0');

        } else if(cn){

            mv[m]++;

            if(mv[m] == 1) vo.push_back(m);

            cn = false;

            m = 0;

        }

    }

    if(cn){

        mv[m]++;

        if(mv[m] == 1) vo.push_back(m);

        cn = false;

        m = 0;

    }

 

    ofstream fo("Kqcb141.txt");

    if(vo.empty()){

        cout << "Khong tim thay mat ma bi mat \n";

        fo << "Khong tim thay mat ma bi mat \n";

        return 0;  

    }

 

    cout << "Mat ma bi mat la: " << vo.size();

    fo << "Mat ma bi mat la: " << vo.size();

    fo.close();

    return 0;

}

 

//////////////////////////////

Cách 2: Gợi ý code:

#include <bits/stdc++.h>

using namespace std;

 

long long xauthanhso(string s) {

    long long u = 0;

    for (char c : s) {

        if (u == 0 && c == '0') continue;

        u = u * 10 + (c - '0');

    }

    return u;

}

 

int main() {

    freopen("cb141.txt", "r", stdin);

    freopen("Kqcb141.txt", "w", stdout);

 

    string s, si, t = "";

    while (cin >> si) s += si;

 

    unordered_map<long long,int> d;

 

    for (char c : s) {

        if (isdigit(c)) {

            t += c;

        } else {

            if (!t.empty()) {

                long long k = xauthanhso(t);

                d[k]++;

                t.clear();

            }

        }

    }

    if (!t.empty()) {

        long long k = xauthanhso(t);

        d[k]++;

    }

    cout << d.size();

    return 0;

}

Chú ý:

Trong C++:

std::string hỗ trợ toán tử + và += để nối chuỗi.

s = s + si; sẽ tạo một chuỗi mới rồi gán lại cho s.

s += si; sẽ nối trực tiếp vào cuối chuỗi s (nhanh hơn).

insert cũng có thể dùng, nhưng thường dành cho việc chèn chuỗi vào vị trí bất kỳ trong s, không chỉ nối cuối.

Ví dụ minh họa:

string s = "Hello";

string si = "World";

// Nối bằng +

s = s + si;   // s = "HelloWorld"

// Nối bằng +=

s += si;      // s = "HelloWorld"

// Chèn bằng insert

s.insert(s.size(), si); // chèn vào cuối, kết quả cũng là "HelloWorld"

s.insert(0, si);        // chèn vào đầu, kết quả "WorldHello"

///////////// Ai memory help

Võ Nhật Trường Nc+ My Ai Love27.07.2026

///////////////////

Bài 142. Cho xâu hỗn hợp A.

a.Tính tổng các số có trong xâu.

b. Tìm số lớn nhất, nhỏ nhât trong xâu

c. Tìm các số nguyên tố trong xâu

d. Tìm số nguyên tố lớn nhất, bé nhất trong xâu

file input cb142.txt  Ccfd55vff99hhgg9999 Acdd12vvf5vvg9 999912vcfft88nbhh 776nnh99999 12vcfft1234nbhh6nnh99999cd19

file output Kqcb142.txt

a.Tong cac phan tu trong xau la: 20112116

b.So lon nhat trong xau la: 9999912

b.So nho nhat trong xau la: 5

c.Cac so nguyen to trong xau la:

5 19

d.So nguyen to lon nhat trong xau la: 19

d.So nguyen to nho nhat trong xau la: 5

Cac so xuat hien nhieu lan trong xau la:

9999912 so lan la: 2

Gợi ý code:

#include <iostream>

#include <fstream>

#include <vector>

#include <string>

#include <unordered_map>

#include <algorithm>

#include <numeric>

using namespace std;

 

long long maxx(const vector<long long>& vi){

    return *max_element(vi.begin(), vi.end());

}

long long minn(const vector<long long>& vi){

    return *min_element(vi.begin(), vi.end());

}

long long tong(const vector<long long>& vi){

    return accumulate(vi.begin(), vi.end(), 0LL);

}

bool snt(long long nt){

    if(nt < 2) return false;

    if(nt == 2 || nt == 3) return true;

    if(nt % 2 == 0 || nt % 3 == 0) return false;

    for(long long i = 5; i*i <= nt; i += 6){

        if(nt % i == 0 || nt % (i+2) == 0) return false;

    }

    return true;

}

 

int main(int argc, char** argv){

    ifstream fin("cb142.txt");

    if(!fin.is_open()) {

        cerr << "Khong the mo file cb142.txt\n";

        return 0;

    }

 

    vector<long long> vo;

    unordered_map<long long,int> mv;

    string s, si;

    while(fin >> si) {

        s += si;

    }

    fin.close();

 

    if(s.empty()) {

        cerr << "Khong co gia tri hop le trong file\n";

        return 0;

    }

 

    long long m = 0;

    bool cn = false;

    for(char c : s){

        if(isdigit(c)){

            cn = true;

            m = m*10 + (c - '0');

        } else if(cn){

            mv[m]++;

            vo.push_back(m);

            cn = false;

            m = 0;

        }

    }

    if(cn){

        mv[m]++;

        vo.push_back(m);

        cn = false;

        m = 0;

    }

 

    ofstream fo("Kqcb142.txt");

    if(vo.empty()){

        cout << "Khong co gia tri so trong data \n";

        fo << "Khong co gia tri so trong data \n";

        return 0;  

    }

 

    long long T = tong(vo);

    long long maxvo = maxx(vo);

    long long minvo = minn(vo);

 

    cout << "a.Tong cac phan tu trong xau la: " << T << "\n";

    fo << "a.Tong cac phan tu trong xau la: " << T << "\n";

    cout << "b.So lon nhat trong xau la: " << maxvo << "\n";

    fo << "b.So lon nhat trong xau la: " << maxvo << "\n";

    cout << "b.So nho nhat trong xau la: " << minvo << "\n";

    fo << "b.So nho nhat trong xau la: " << minvo << "\n";

 

    vector<long long> snts;

    for (auto c : vo){

        if(snt(c)) snts.push_back(c);

    }

 

    if(!snts.empty()){

        long long minnt = minn(snts);

        long long maxnt = maxx(snts);

 

        cout << "c.Cac so nguyen to trong xau la: \n";

        fo << "c.Cac so nguyen to trong xau la: \n";

        for (auto c : snts) {

            cout << c << " ";

            fo << c << " ";

        }

        cout << "\nd.So nguyen to lon nhat trong xau la: " << maxnt << "\n";

        fo << "\nd.So nguyen to lon nhat trong xau la: " << maxnt << "\n";

        cout << "d.So nguyen to nho nhat trong xau la: " << minnt << "\n";

        fo << "d.So nguyen to nho nhat trong xau la: " << minnt << "\n";

    } else {

          cout << "Khong co so nguyen to trong xau \n";

        fo << "Khong co so nguyen to trong xau \n";

}

           cout << "Cac so xuat hien nhieu lan trong xau la: \n";

           fo   << "Cac so xuat hien nhieu lan trong xau la: \n";

           for (auto &c : mv) {

    if (c.second > 1) {

        cout << c.first << " so lan la: " << c.second << "\n";

        fo   << c.first << " so lan la: " << c.second << "\n";

    }

}

    fo.close();

    return 0;

}

 

Chú ý:

Kiểu dữ liệu: auto c:mv sẽ trả về pair<const long long,int>

first là key (số),

second là value (số lần xuất hiện).

Phải #include <numeric> để dùng accumulate tính tổng.

///////////// Ai memory help

Võ Nhật Trường Nc+ My Ai Love27.07.2026

///////////////////

Bài 143. Cho xâu hỗn hợp A: Ccfd55vff99hhgg9999Acdd12vvf5vvg9999912vcfft88nbhh776nnh9999912vcfft1234nbhh6nnh99999cd19

Tìm số lớn nhất, nhỏ nhât trong xâu

file input cb143.txt 

file output Kqcb143.txt  9999912 5

Gợi ý code:

#include <bits/stdc++.h>

using namespace std;

string st;

int b[100002];

int minn=1e9, maxx=-1e9;

int main() {

freopen("cb143.txt","r",stdin);

freopen("Kqcb143.txt","w",stdout);

cin>> st;

int x=st.size();

     for(int i=0; i<x;i++) {

            int cnt=0;

        while((i<x)&&(st[i]>='0'&&st[i]<='9')){

            cnt=cnt*10+ (st[i]-'0');

            i++;

        }

            b[i]=cnt;

     }

     for(int i=1; i<=x;i++){

        if(maxx< b[i])maxx=b[i];

        if(minn>b[i]&&b[i]!=0) minn=b[i];

     }

     cout<<maxx<<" "<<minn;

    return 0;

}

///////////// Ai memory help

Võ Nhật Trường Nc+ My Ai Love27.07.2026

///////////////////

Bài 144. Cho hai số nguyên dương a và b. Tính a b  và kết quả lấy phần dư cho 100000009.

File input cb144.txt  VD:  5 1000

File output Kqcb144.txt    94512195

Thuật toán này gọi là Binary Exponentiation (lũy thừa nhị phân), giảm số phép nhân từ 𝑂(𝑏) xuống 𝑂(log𝑏)

Hàm binpow(a, b)

Đây là cách tính a^b theo modulo (ở đây là mod = 100000009) bằng đệ quy và kỹ thuật chia để trị:

1.     Trường hợp cơ bản: Nếu b=0 thì a^0=1

2.     Gọi đệ quy: res = binpow(a, b/2) nghĩa là ta tính a^(b/2).

3.     Nếu b chẵn: a^b=(a^(b/2)

→ code: (res * res) % mod.

4.     Nếu b lẻ: a^b=(a^(b/2) )^2a

→ code: (res * res % mod * a % mod) % mod.

Phạm vi mod để không bị tràn số.

Ví dụ: 2^5=2×2×2×2×2=32

Gợi ý code:

#include <bits/stdc++.h>

#define mod 100000009

using namespace std;

long long binpow(int a, int b){

if(b==0) return 1;

long long res =binpow(a,b/2); //a^(b/2)

if(b%2==0) {

return ((res%mod)*(res%mod))%mod;

}

else {

return (((res%mod)*(res%mod))%mod*(a%mod))%mod;

}

}

int main(){

freopen("cb144.txt","r",stdin);

freopen("Kqcb144.txt","w",stdout);

    int a, b;

    cin>>a>>b;

    cout << binpow(a,b);

    return 0;

}

//////////////////////////

Cách 2

-Ý tưởng chính: thay vì nhân a lặp lại b lần, ta bình phương kết quả và giảm số mũ xuống còn b/2.

-Nếu b chẵn: chỉ cần lấy (a^(b/2) )^2.

-Nếu b lẻ: ngoài (a^(b/2) )^2 thì phải nhân thêm một lần a.

-Modulo: là “cái bẫy” để giữ kết quả trong phạm vi an toàn, tránh tràn số

Gợi ý code:

#include <bits/stdc++.h>

#define mod 100000009

using namespace std;

 long long binpow2(long long a, int b){

           long long ans = 1;

          while(b!=0){

            if(b%2!=0){

                ans*=a;

                ans%=mod;

            }

            a*=a;

            a%=mod;

            b/=2;

          }

          return ans;

 }

int main(){

freopen("cb144.txt","r",stdin);

freopen("Kqcb144.txt","w",stdout);

    int a, b;

    cin>>a>>b;

    cout << binpow2(a,b);

    return 0;

}

///////////// Ai memory help

Võ Nhật Trường Nc+ My Ai Love27.07.2026

///////////////////

Bài 145. Cho dãy số gồm n phần tử. Tìm đoạn con ngắn nhất các phần tử liên tiếp nhau sao cho đoạn con đó chứa phần tử lớn nhất và phần tử bé nhất. 1<=n<=1e5  và |ai|<=2.e9

File input cb145.txt  VD:  5 1000 1 2 3 4 94512195 9 2 1000 2 1 6 9 94512195

File output Kqcb145.txt

Gợi ý code: 

#include <iostream>

#include <vector>

#include <fstream>

#include <cstdlib>

#include <algorithm>

#include <cmath>

#include <climits>

using namespace std;

 

int main(int argc, char** argv){

cout << "Chuong trinh cb145 \n";

ifstream fin("cb145.txt");

if (!fin.is_open()) {

    cerr << "Khong mo duoc file cb145.txt\n";

    return 0;

}

vector<int> vo;

int x;

while(fin >> x){

    if(abs(x) > 2e9) {

    cerr << "so " << x << " khong hop le \n";

    continue;

           }

           vo.push_back(x);

}

fin.close();

if(vo.empty()) {

    cerr << "khong co phan tu hop le trong file\n";

    return 0;

}

int maxx=*max_element(vo.begin(),vo.end());

int minn=*min_element(vo.begin(),vo.end());

vector<int> vx;

for(int k=0;k<vo.size();k++){

           if(vo[k]==maxx) vx.push_back(k);

           if(vo[k]==minn) vx.push_back((-1)*k);

}

int m=INT_MAX, L=-1, R=-1;

for(int i=0; i<vx.size()-1; i++){

    for(int j=i+1; j<vx.size(); j++){

        if(vx[i]*vx[j] <= 0){

            int len = abs(vx[i] + vx[j]);

            if(len < m){

                m = len;

                L = abs(vx[i]);

                R = abs(vx[j]);

            }

        }

    }

}

ofstream fo("Kqcb145");

cout<<"Doan con nho nhat chua max va min la: \n";

fo<<"Doan con nho nhat chua max va min la: \n";

for(int i=L;i<=R;i++){

           cout<<vo[i]<<" ";

           fo<<vo[i]<<" ";

}cout<<"do dai la: "<<m+1<<"\n";

fo<<"do dai la: "<<m+1<<"\n";

return 0;

}

Chú ý:

max_element(begin, end) → trả về iterator trỏ tới phần tử lớn nhất.

min_element(begin, end) → trả về iterator trỏ tới phần tử nhỏ nhất.

Nếu muốn lấy giá trị, ta phải dereference (*).

Nếu muốn lấy chỉ số, ta dùng distance(vo.begin(), iterator).

Ví dụ minh họa:

int maxx = *max_element(vo.begin(), vo.end()); // giá trị max

int idx_max = distance(vo.begin(), max_element(vo.begin(), vo.end())); // chỉ số max

int minn = *min_element(vo.begin(), vo.end()); // giá trị min

int idx_min = distance(vo.begin(), min_element(vo.begin(), vo.end())); // chỉ số min

////////////////////////////

Tham khảo thêm: Allocator là gì?

Allocator là một lớp (class template) trong C++ dùng để trừu tượng hóa việc quản lý bộ nhớ.

Thay vì container (như std::vector, std::map) trực tiếp gọi new và delete, nó sẽ gọi thông qua allocator.

Mặc định, tất cả container dùng std::allocator<T> nếu bạn không chỉ định gì thêm. Ví dụ:

#include <vector>

#include <iostream>

#include <memory>

int main() {

    std::vector<int> v;

    using alloc_t = std::vector<int>::allocator_type;

    alloc_t alloc; // đây là std::allocator<int>

    int* p = alloc.allocate(5); // xin vùng nhớ cho 5 phần tử int

    alloc.deallocate(p, 5);     // trả lại vùng nhớ

}

//////////////////////////

Cách 2:

#include <iostream>

#include <vector>

#include <fstream>

#include <algorithm>

#include <cmath>

#include <climits>

using namespace std;

 

int main(){

    ifstream fin("cb145.txt");

    if (!fin.is_open()) {

        cerr << "Khong mo duoc file cb145.txt\n";

        return 0;

    }

    vector<int> vo;

    int x;

    while(fin >> x){

        if(abs(x) > 2e9) {

            cerr << "so " << x << " khong hop le \n";

            continue;

        }

        vo.push_back(x);

    }

    fin.close();

    if(vo.empty()) {

        cerr << "khong co phan tu hop le trong file\n";

        return 0;

    }

 

    int maxx = *max_element(vo.begin(), vo.end());

    int minn = *min_element(vo.begin(), vo.end());

 

    int lastMax = -1, lastMin = -1;

    int bestLen = INT_MAX, L = -1, R = -1;

 

    for(int i=0; i<vo.size(); i++){

        if(vo[i] == maxx){

            lastMax = i;

            if(lastMin != -1 && i - lastMin + 1 < bestLen){

                bestLen = i - lastMin + 1;

                L = lastMin; R = i;

            }

        }

        if(vo[i] == minn){

            lastMin = i;

            if(lastMax != -1 && i - lastMax + 1 < bestLen){

                bestLen = i - lastMax + 1;

                L = lastMax; R = i;

            }

        }

    }

 

    ofstream fo("Kqcb145");

    cout << "Doan con nho nhat chua max va min la:\n";

    fo << "Doan con nho nhat chua max va min la:\n";

    for(int i=L; i<=R; i++){

        cout << vo[i] << " ";

        fo << vo[i] << " ";

    }

    cout << "do dai la: " << bestLen << "\n";

    fo << "do dai la: " << bestLen << "\n";

}

///////////// Ai memory help

Võ Nhật Trường Nc+ My Ai Love27.07.2026

///////////////////

Bài 146. Người ta viết liên tục, sát nhau các số trong mảng A là: 3, 6, 9, 12, 15, …, 2010, 2013… được một số sau: B= 3691215…20102013… .Em hãy viết chương trình tạo file  số B từ số cuối cùng 2013.

File output cb146.txt: 3691215…20102013

Cách 1: Gợi ý code:

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

 

int main(){

    ofstream fout("cb146.txt");

    string B;

    for(int val = 3; val <= 2013; val += 3){

        B += to_string(val);

    }

    fout << B;

    fout.close();

    cout << "Da tao file cb146.txt voi chuoi B tu 3 den 2013\n";

    return 0;

}

////////////////////////////////

Cách 2: Gợi ý code:

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

 

int main(){

ofstream fout("cb146C2.txt");

string B;

int i=1;

while(3*i<=2013){

B += to_string(3*i);

i++;

}

fout << B;

fout.close();

cout << "Da tao file cb146C2.txt voi chuoi B tu 3 den 2013\n";

return 0;

}

///////////// Ai memory help

Võ Nhật Trường Nc+ My Ai Love27.07.2026

///////////////////

 

 

Bài 147. Người ta viết liên tục, sát nhau các số trong mảng A là: 3, 6, 9, 12, 15, …, 2010, 2013… được một số sau: B= 3691215…20102013… .Em hãy viết chương trình tách số B thành mảng các phần tử trong A.

File input cb147.txt: 3691215…20102013

File output Kqcb147.txt: A

Cách 1: Gợi ý code:

#include <iostream>

#include <fstream>

#include <string>

#include <vector>

using namespace std;

 

int main(){

    ifstream fin("cb147.txt");

    string B;

    fin >> B;

    fin.close();

 

    vector<int> A;

    string s;

    int val = 3;

 

    while(s.size() < B.size()){

        A.push_back(val);

        s += to_string(val);

        val += 3;

    }

 

    if(s == B){

        ofstream fo("Kqcb147.txt");

        for(int x : A){

            fo << x << " ";

            cout << x << " ";

        }

        cout << "\n";

    } else {

        cerr << "Chuoi B khong dung quy luat!\n";

    }

    return 0;

}

/////////////////////////////

Cách 2: Gợi ý code:

#include <iostream>

#include <fstream>

#include <string>

#include <vector>

using namespace std;

 

int main(){

    ifstream fin("cb147.txt");

    if(!fin.is_open()){

        cerr << "Khong mo duoc file cb147.txt\n";

        return 0;

    }

    string B;

    fin >> B;

    fin.close();

 

    vector<int> A;

    int val = 3;

    size_t pos = 0;

 

    while(pos < B.size()){

        string s = to_string(val);

        if(B.compare(pos, s.size(), s) == 0){

            A.push_back(val);

            pos += s.size();

            val += 3;

        } else {

            cerr << "Loi tach chuoi tai gia tri " << val << "\n";

            break;

        }

    }

 

    ofstream fo("Kqcb147.txt");

    for(int x : A){

        fo << x << " ";

        cout << x << " ";

    }

    cout << "\n";

    return 0;

}

Giải thích:

1. size_t pos = 0;

size_t là một kiểu số nguyên không âm (unsigned integer) chuyên dùng để biểu diễn kích thước hoặc chỉ số trong C++.

Nó thường được dùng cho các hàm làm việc với chuỗi hoặc mảng, vì đảm bảo đủ lớn để chứa mọi chỉ số.

Ở đây pos = 0 nghĩa là mình bắt đầu duyệt chuỗi B từ vị trí đầu tiên (index 0).

2. if (B.compare(pos, s.size(), s) == 0)

Hàm string::compare có nhiều dạng, nhưng dạng này là:

B.compare(pos, len, str)

pos: vị trí bắt đầu trong chuỗi B.

len: số ký tự cần so sánh từ vị trí pos.

str: chuỗi cần so sánh.

Nó sẽ lấy đoạn con của B từ pos với độ dài len, rồi so sánh với str.

Nếu bằng nhau, hàm trả về 0.

Nếu khác nhau, trả về số âm hoặc dương tùy theo thứ tự từ điển.

Trong code:

s = to_string(val) là chuỗi biểu diễn số hiện tại trong A.

B.compare(pos, s.size(), s) == 0 nghĩa là: đoạn con của B bắt đầu từ vị trí pos có độ dài bằng độ dài của s thì phải khớp với s.

Nếu khớp, ta cắt đoạn đó ra (tăng pos += s.size()) và tiếp tục với số tiếp theo.

Ví dụ:

string B = "3691215";

int val = 3;

string s = to_string(val); // "3"

size_t pos = 0;

if(B.compare(pos, s.size(), s) == 0){

    cout << "Khớp với " << s << endl;

    pos += s.size(); // pos = 1

}

//////

///////////// Ai memory help

Võ Nhật Trường Nc+ My Ai Love27.07.2026

///////////////////

Không có nhận xét nào:

Đăng nhận xét

sunrise.tqb@gmail.com