Trong bài toán này, ta được cho mảng nhị phân bin[] và Q truy vấn, mỗi truy vấn gồm hai giá trị L và R. Nhiệm vụ là tạo chương trình giải quyết truy vấn: giá trị thập phân của mảng con của mảng nhị phân trong C++.
Mô tả bài toán
Để giải mỗi truy vấn, ta phải tìm và in ra số thập phân được tạo bởi mảng con từ L đến R, tức subarray[L...R].
Ví dụ minh họa
Đầu vào
bin[] = {1, 1, 0, 0, 1, 0, 1, 0, 0, 0}
Q = 2
2 5
0 6
Đầu ra
2 101
Giải thích
Truy vấn 1: mảng con là {0, 0, 1, 0}. Tạo số nhị phân 0010, chuyển thập phân = 2.
Truy vấn 2: mảng con là {1, 1, 0, 0, 1, 0, 1}. Tạo số nhị phân 1100101, chuyển thập phân = 101.
Phương pháp giải
Cách đơn giản: duyệt mảng nhị phân từ chỉ số L đến R, tìm số nhị phân tạo thành, rồi chuyển sang thập phân.
Chương trình triển khai:
Ví dụ
#include <iostream>
#include <math.h>
using namespace std;
int CalcDecimalValue(int bin[], int L, int R) {
int decimal = 0;
int j = 0;
for(int i = R; i >= L; i--) {
decimal += bin[i] * pow(2, j);
j++;
}
return decimal;
}
int main() {
int bin[] = {1, 1, 0, 0, 1, 0, 1, 0, 0, 0};
int n = sizeof(bin) / sizeof(bin[0]);
int Q = 2;
int query[Q][2] = {{2, 5},{0, 6}};
for(int i = 0; i < Q; i++) {
cout << "For query " << (i+1) << ": The decimal value of subarray is "
<< CalcDecimalValue(bin, query[i][0], query[i][1]) << "\n";
}
return 0;
}
Đầu ra
For query 1: The decimal value of subarray is 2 For query 2: The decimal value of subarray is 101
Cách tiếp cận khác dùng mảng tiền tính. Tạo mảng decimalArray lưu số thập phân tạo được từ chỉ số i đến cuối mảng. Khi truy vấn, lấy hiệu giữa giá trị tại L và R.
Giá trị tại i: decimalArray[i] = bin[i]*2^(n-1-i) + bin[i+1]*2^(n-1-i+1) + ... + bin[n-1]*2^0.
Chương trình minh họa:
Ví dụ
#include <bits/stdc++.h>
using namespace std;
int decimalArray[1000];
void createDecimalArray(int bin[], int n) {
memset(decimalArray, 0, n*sizeof(int));
decimalArray[n - 1] = bin[n - 1] * pow(2, 0);
for (int i = n - 2; i >= 0; i--)
decimalArray[i] = decimalArray[i + 1] + bin[i] * (pow(2, (n - 1 - i)));
}
int CalcDecimalValue(int L, int R, int n) {
if (R != n - 1)
return (decimalArray[L] - decimalArray[R + 1]) / (pow(2, (n - 1 - R)));
return decimalArray[L] / (1 << (n - 1 - R));
}
int main() {
int bin[] = {1, 1, 0, 0, 1, 0, 1, 0, 0, 0};
int n = sizeof(bin) / sizeof(bin[0]);
createDecimalArray(bin, n);
int Q = 2;
int query[Q][2] = {{2, 5},{0, 6}};
for(int i = 0; i < Q; i++) {
cout << "For query " << (i+1) << ": The decimal value of subarray is "
<< CalcDecimalValue(query[i][0], query[i][1], n) << "\n";
}
return 0;
}
Đầu ra
For query 1: The decimal value of subarray is 2 For query 2: The decimal value of subarray is 101