Code Dsa
Code Dsa
Code Dsa
Input
The Text
Output
Example
Input
Output
12
//C
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
int number =0;
char a[10000];
int count =0;
char word;
while (scanf("%c", &word) != EOF)
{
a[count] = word;
count ++;
}
char *part = NULL;
part = strtok(a, " \t\n");
while (part != NULL)
{
number ++;
part = strtok(NULL, " \t\n");
}
printf("%d", number);
}
Input
The TEXT
Output
Example
Input
Hello John,
Bye,
Output
HELLO JOHN,
BYE,
//C
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(){
char a[100000];
int count=0;
char word;
while (scanf("%c", &word) != EOF)
{
a[count] = word;
count++;
}
for (int i=0; i<strlen(a);i++)
{
if (isalpha(a[i])) a[i] = toupper(a[i]);
}
printf("%s", a);
return 0;
}
Input
Output
Example
Input
Output
-6 -3 -2 -1 1 2 3 6
//C
#include <stdio.h>
int main() {
int x;
scanf("%d", &x);
for (int i = -x; i <= x; i++) {
if (i!=0 && x % i == 0) printf("%d ", i);
}
return 0;
}
Chapter 1 - Sum Array
Description
Given a sequence of integers a1, a2, ..., an. Compute the sum Q of elements of this sequence.
Input
Output
Example
Input
3254
Output
14
//C
#include <stdio.h>
int main() {
int N;
scanf("%d", &N);
int t;
int sum;
for (int i=0; i<N;i++)
{
scanf("%d", &t);
sum += t;
}
printf("%d", sum);
}
Chapter 1 - Bounding rectangle
Cho một danh sách các hình chữ nhật 1, 2,…, n. Hãy tìm diện tích hình chữ nhật nhỏ nhất bao tất cả
các hình chữ nhật trong danh sách trên
Dữ liệu
· Dòng i+1 (i=1,…,n): chứa 4 số nguyên dương x1,y1, x2,y2 trong đó (x1,y1) và (x2,y2) là tọa độ 2 đỉnh
đối của hình chữ nhật thứ i (1 <= x1, y1, x2, y2 <= 100)
Kết quả
· Ghi ra diện tích của hình chữ nhật nhỏ nhất tìm được
Ví dụ
Dữ liệu
3
2427
3247
1252
Kết quả
20
#include <stdio.h>
#include <limits.h>
int main()
{
int N;
scanf("%d", &N);
int maxx = INT_MIN;
int minx = INT_MAX;
int maxy= INT_MIN;
int miny= INT_MAX;
for (int i=0; i<N; i++)
{
int x1 =0; int y1=0; int x2=0; int y2=0;
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
if (x1<minx) minx=x1;
if(x1>maxx) maxx=x1;
if (x2<minx) minx=x2;
if(x2>maxx) maxx=x2;
if (y1<miny) miny=y1;
if(y1>maxy) maxy=y1;
if (y2<miny) miny=y2;
if(y2>maxy) maxy=y2;
}
int area = (maxx- minx) * (maxy-miny);
printf("%d", area);
}
Chapter 1 - Replace characters in string
Description
Write a function that gets a string and two chars as arguments. The functions scans the string and
replaces every occurrence of the first char with the second one.
Write a program to test the above function. The program should read a string from the user (no
spaces) and two characters, then call the function with the input, and print the result.
For example
- output: “mama”
//C
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
char first;
char second;
scanf("%100s", str);
scanf(" %c", &first);
scanf(" %c", &second);
for (int i=0; i<strlen(str);i++)
{
if(str[i] == first)
{
str[i] = second;
}
}
printf("%s", str);
return 0;
}
Input
Ouput
Example
Input
35
Output
8
//C
#include <stdio.h>
#include <string.h>
if (carry) {
// If there's a carry after adding all digits
for (int i = maxLength; i > 0; i--) {
result[i] = result[i - 1];
}
result[0] = carry + '0'; // Convert integer to char
}
return result;
}
int main() {
char num1[MAX_LENGTH], num2[MAX_LENGTH];
Input
o Line 2: a1,…,an
o Line 3: b1,…,bm
Output
Write to stdout T lines, each line t contains 1 if the sequences of the t th test are equal, and write 0,
otherwise.
Example
Input
3331231234212341233241231
Output
100
//C
#include <stdio.h>
int main() {
int T;
scanf("%d", &T);
if (m != n) {
printf("0\n");
} else {
int dem = 0;
for (int i = 0; i < m; i++) {
if (a[i] == b[i]) dem++;
}
if (dem == m) {
printf("1\n");
} else {
printf("0\n");
}
}
}
return 0;
}
Chapter 1 - Text Replacement
Description
Cho văn bản T và 2 mẫu P1, P2 đều là các xâu ký tự (không chứa ký tự xuống dòng, độ dài không
vượt quá 1000). Hãy thay thế các xâu P1 trong T bằng xâu P2.
Dữ liệu
· Dòng 1: xâu P1
· Dòng 2: xâu P2
Kết quả:
Ví dụ
Dữ liệu
AI
Artificial Intelligence
Kết quả
Recently, Artificial Intelligence is a key technology. Artificial Intelligence enable efficient operations in
many fields.
#include <stdio.h>
#include <string.h>
int main() {
char P1[MAX_LENGTH], P2[MAX_LENGTH], T[MAX_LENGTH];
// Nhập dữ liệu
fgets(P1, MAX_LENGTH, stdin);
fgets(P2, MAX_LENGTH, stdin);
fgets(T, MAX_LENGTH, stdin);
// In kết quả
printf("%s\n", T);
return 0;
}
Problem: Chapter 1 - Sum Array
Description
Given a sequence of n integers a1, ..., an. Compute the sum of elements
Input
Output
Example
Input
1234
Output
10
//C
#include <stdio.h>
int main()
{
int N;
scanf("%d", &N);
int sum =0;
int tem;
for (int i=0; i<N; i++)
{
scanf("%d", &tem);
sum += tem;
}
printf("%d", sum);
}
Problem: Chapter 1 - Multiplication of 2 matrices
Description
Given two matrices An x k and Bk x m. Each element of the two matrices are integers from 1 to 50.
Compute the product matrix C = A x B.
Input
Output
Line i (i = 1,...,n) contains the ith row of the resulting matrix (elements are separated by a SPACE
character)
Example
Input
23
123
456
34
1111
2222
3333
Output
14 14 14 14
32 32 32 32
#include <stdio.h>
int main() {
int n, k1, k2, m;
Description
Given a matrix T having n rows and m columns, each element is 0 or 1. A column is called black
column if each element on this column is 1. Write a program to compute the number Q of black
columns
Input
Line 1: contains two positive integers n and m (1 <= n,m <= 1000)
Line i+1 (i = 1,...,n): contains the ith row of the matrix T
Output
Example
Input
44
1010
1110
1011
1111
Ouput
#include <stdio.h>
int main() {
int n, m;
int blackColumnsCount = 0;
return 0;
}
Problem: Chapter 1 - k-Subsequence even
Description
Given a sequence of integers a1, a2, . . ., an. A k-subsequence is define to be a sequence of k
consecutive elements: ai, ai+1, . . ., ai+k-1. The weight of a k-subsequence is the sum of its elements.
Given positive integers k and m. Compute the number Q of k-subsequences such that the weight is
even.
Input
Line 1: contains 2 positive integers n, k (1 <= n <= 100000, 1 <= k <= n/2)
Line 2: contains a1, a2, . . ., an. (1 <= ai <= 10000)
Output
Write the value Q
Example
Input
63
245112
Output
//C
#include <stdio.h>
int main() {
int n, k;
scanf("%d %d", &n, &k);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int even_count = 0;
printf("%d\n", even_count);
return 0;
}
Problem: Chapter 1 - Report student doing quiz on date
Description
Cần thống kê xem mỗi ngày có bao nhiêu lượt sinh viên làm trắc nghiệm.
Input
Thông tin về sinh viên làm trắc nghiệm ôn tập được cho theo các dòng định dạng như sau:
<yyyy-mm-dd> <hh:mm:ss> <user_id> <question_id>: trong đó sinh viên có mã <user_id> làm câu
hỏi <question_id> vào ngày giờ là <yyyy-mm-dd> <hh:mm:ss>
Output
Mỗi dòng ghi <yyyy-mm-dd> <cnt>: trong đó <cnt> là số lượt sinh viên làm trắc nghiệm trong
ngày <yyyy-mm-dd>
(chú ý: các dòng được sắp xếp theo thứ tự tăng dần của ngày thống kê, ngày thống kê nào mà
không có lượt sinh viên làm trắc nghiệm thì không in ra)
Example
Input
Output
2022-01-02 2
2022-01-03 1
2022-02-01 2
2022-03-01 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char d[11];
char t[9];
char m[20];
char h[20];
}im;
im *L=malloc(n1*sizeof(im));
im *R=malloc(n2*sizeof(im));
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0; j = 0; k = l;
while (i < n1 && j < n2) {
if (strcmp(L[i].d, R[j].d)<=0) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
free(L); free(R);
}
void mergeSort(im arr[], int l, int r)
{
if (l < r) {
int m = (r + l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main()
{
int i=0;
im b[100000];
while(1){
scanf("%[^ \n]%*c", b[i].d);
if(!strcmp(b[i].d, "*")) break;
scanf("%[^ ]%*c", b[i].t);
scanf("%[^ ]%*c", b[i].m);
scanf("%[^\n]%*c", b[i].h);
i++;
}
mergeSort(b, 0, i-1);
int k, count; k=count=0;
for(int j=0; j<i; j++){
if(!strcmp(b[k].d, b[j].d)) count++;
else{
printf("%s %d\n", b[k].d, count);
k=j; j--; count=0;
}
}
printf("%s %d", b[k].d, count);
return 0;
}
Problem: Chapter 1 - Solve degree-2 polynomial equation
Description
Given an equation ax^2 + bx + c = 0. Find solution to the given equation.
Input
Output
Write NO SOLUTION if the given equation has no solution
Write x0 (2 digits after the decimal point) if the given equation has one solution x0
Write x1 and x2 with x1 < x2 (2 digits after the decimal point) if the given equation has
two distinct solutions x1, x2
Example
Input
118
Output
NO SOLUTION
Input
1 -2 1
Output
1.00
Input
1 -7 10
Output
2.00 5.00
//C
#include <stdio.h>
#include <math.h>
int main() {
int a;
int b;
int c;
int delta;
float x0;
float x1;
float x2;
if (delta > 0) {
x1 = (-b - sqrt(delta))/(2*a);
x2 = (-b + sqrt(delta))/(2*a);
printf("%.2f\n%.2f\n", x1, x2); // Added newline characters
}
else if (delta == 0) {
x0 = -b / (2*a);
printf("%.2f\n", x0); // Added newline character
}
else {
printf("NO SOLUTION\n");
}
return 0;
}
Problem: Chapter 1 - Find integer solutions to Polynomial Degree 3
Description
Given 3 integers a, b, c (c != 0). Write a program that find distinct integers solution s1, s2, . . ., sk)
such that x3 + ax2 + bx + c can be rewritten under the form (x-s1) m1(x-s2)m2. . . (x-sk)mk in which m1,
m2, . . ., mk are call multipliers.
Input
Output
In case that no solution found, then write NO SOLUTION to stdout. Otherwise, write the solution
under the format:
s1 m1
s2 m2
s3 m3
...
in which s1, s2, s3, ... are solution sorted in an increasing order and m1, m2, m3, ... are respectively
the multipliers of s1, s2, s3, ...
Example
Input
-1 -1 -2
Output
NO SOLUTION
Input
-6 11 -6
Output
11
21
31
Input
8 5 -50
Output
-5 2
21
#include <stdio.h>
#include <stdlib.h>
int a, b, c;
return 0;
}
Problem: Chapter 1 - Check Sudoku
Description
A matrix 9 x 9 is called a sudoku solution if it satisfies following constraints
Input
Output
Contains T lines, each line i (i = 1, 2, ..., T) contains 1 if the ith matrix is a sudoku solution,
and contains 0, otherwise
Example
Input
123456789
456789123
789123456
214365897
365897214
897214365
531678942
972541638
648932571
123456789
456789123
789123456
214365897
365897214
897214365
531678942
978542631
442931578
Output
#include <stdio.h>
#include <stdbool.h>
int main() {
int T;
scanf("%d", &T);
return 0;
}
Problem: Chapter 1 - Evaluate expression contains + * operand
Description
Given a string representing a math expression including operator + and * and operands which are
positive integers. Compute the value Q of this expression.
Input
Line 1: contains the string representing the expression (number of operators is upto
10000)
Output
Write the value Q modulo 109+7 if the expression is mathematically correct in term of
the syntax, and write NOT_CORRECT, otherwise
Example
Input
5+7*3*10*10
Output
2105
Input
5*+ 7*3*10*10
Output
NOT_CORRECT
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char str[300009];
scanf("%s", str);
unsigned long long result=1, sum=0;
char *token=strtok(str, "+");
while(token !=NULL)
{
unsigned long long count=0;
unsigned long long result2=1;
unsigned long long ad=0;
unsigned long long result1=0;
for(unsigned long long i=0; i<strlen(token); i++)
{
if(token[i] != '*'){
count++;
}
else{
result1=0;
for(unsigned long long j=ad; j<i; j++)
{
result1+=(token[j]-'0')*pow(10,count-1);
count--;
}
ad=i+1;
result2 *=result1;
}
}
result1=0;
while(count !=0)
{
result1 += (token[ad]-'0')*pow(10,count-1);
ad++;
count--;
}
result2 =result2*result1;
sum+=result2;
token=strtok(NULL, "+");
}
unsigned long long ans =sum%((int) 1e9+7);
printf("%llu", ans);
}
Problem: Chapter 1 - Basic queries on array
Description
Given a sequence of integers a1, a2, ..., an. Perform a sequence of queries over this sequence
including:
Input
The first block contains the information about the given sequence with the following
format:
o Line 2: contains n integers a1, a2, ..., an (-1000 <= ai <= 1000)
The second block contains a sequence of queries defined above, each query is in a line.
The second block is terminated a 3 characters ***
Output
Example
Input
14325
find-max
find-min
find-max-segment 1 3
find-max-segment 2 5
sum
***
Output
15
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int n, i, j;
int arr[MAX_N];
char query[50];
// Process queries
while (1) {
scanf("%s", query);
if (strcmp(query, "***") == 0) {
break;
} else if (strcmp(query, "find-max") == 0) {
int max = MIN_INT;
for (i = 0; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
printf("%d\n", max);
} else if (strcmp(query, "find-min") == 0) {
int min = MAX_INT;
for (i = 0; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
printf("%d\n", min);
} else if (strcmp(query, "sum") == 0) {
int sum = 0;
for (i = 0; i < n; i++) {
sum += arr[i];
}
printf("%d\n", sum);
} else if (strncmp(query, "find-max-segment", 16) == 0) {
int i, j;
scanf("%d %d", &i, &j);
i--; // Convert to zero-based index
j--; // Convert to zero-based index
int max_segment = MIN_INT;
for (int k = i; k <= j; k++) {
if (arr[k] > max_segment) {
max_segment = arr[k];
}
}
printf("%d\n", max_segment);
}
}
return 0;
}
Problem: Chapter 1 - Find all perfect square in a sequence
Description
Given a sequence of n integers a1, a2, . . ., an. Compute the number Q of perfect squares (the
number of type a2) of that sequence.
Input
Output
Example
Input
32479
Output
//C
#include <stdio.h>
#include <math.h>
return 0;
}
Problem: Chapter 1 - Separate the integer and decimal parts of a float
Description
Given a float number A, the integer part I is defined to be the largest integer that is less than or
equal to A, and the decimal part D is defined to be A - I. Compute the integer and decimal parts of A.
Input
Output
Write the integer and decimal parts of A (separated by a SPACE character) (the decimal
part is written with 2 digits after the decimal point)
Example
Input
2.57902
Output
2 0.58
Input
-4.3456
Output
-5 0.65
//C
#include <stdio.h>
#include <math.h>
int main()
{
float N;
scanf("%f", &N);
int k;
if(N>=0)
{
k = (int) (N);
}
else
{
k = (int) (N) -1;
}
float left = N -k;
printf("%d %.2f", k, left);
return 0;
}
Problem: Chapter 1 - Black colums of 0-1 matrix
Description
Given a 0-1 matrix of size n (n rows and n columns). Compute the number Q of columns of the given
matrix in which all the element of the column are 1.
Input
Output
Example
Input
11111
11110
10111
11111
10110
Output
//C
#include <stdio.h>
int main()
{
int N;
scanf("%d", &N);
int matrix [1000][1000] = {0};
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
scanf("%d", &matrix[i][j]);
}
}
int dem =0;
int count=0;
for (int i=0; i<N; i++)
{
for (int j=0; j<N;j++)
{
if((matrix[j][i]) ==1) dem++;
}
if (dem == N) count++;
dem =0;
}
printf("%d", count);
return 0;
}
Problem: Chapter 1 - Check Queen solution
Description
Given a chess board N x N on which there are N being placed in N different cells.
Write a program that check if there are two queen, that attacks each other.
A board is represented by a NxN matrix A in which A[i,j] = 1 if there is a queen placed in cell (i,j), and
A[i,j] = 0, otherwise.
Input
Line 1: contains a positive integer T which is the number of test-cases (1 <= T <= 100)
T following block, each block is the input of a test-case with the format:
Output
In each line t (t = 1, 2, ..., T), write 1 if in the test-case t, there are no two queen that
attack each other, and write 0, otherwise
Example
Input
0100
0001
1000
0010
0100
0000
1001
0010
Output
#include <stdio.h>
// Check diagonals
for (int i = 0; i < N; i++) {
int diag1Sum = 0;
int diag2Sum = 0;
for (int j = 0; j < N; j++) {
diag1Sum += board[j][j];
diag2Sum += board[j][N - 1 - j];
}
if (diag1Sum > 1 || diag2Sum > 1) {
return 1;
}
}
return 0;
}
int main() {
int T;
scanf("%d", &T);
// Free memory
for (int i = 0; i < N; i++) {
free(board[i]);
}
free(board);
}
return 0;
}
CHAPTER 2:
Problem: Chapter 2 - Permutation generation
Description
Given an integer n, write a program to generate all permutations of 1, 2, ..., n in a lexicalgraphic order
(elements of a permutation are separated by a SPACE character).
Example
Input
Output
123
132
213
231
312
321
#include <stdio.h>
#define P 1000000007
int X[21];
int N;
int checked[21];
void printout()
{
for (int i=1; i<=N; i++)
{
printf("%d ", X[i]);
}
printf("\n");
}
void Try (int i)
{
for (int k=1; k<=N; k++)
{
if (checked[k] ==0)
{
X[i] =k;
checked[k] = 1;
if (i==N)
{
printout();
}
else
{
Try(i+1);
}
checked[k] = 0;
}
}
}
int main()
{
for (int i=0; i<=21; i++)
{
X[i] = 0;
checked[i] =0;
}
scanf("%d", &N);
Try(1);
return 0;
}
Problem: Chapter 2 - Linear Integer Equation - coefficent 1
Description
Given two integer n and M. Write a program that generates all ordered collection (X1, X2, ..., Xn) such
that: X1 + X2 + . . . + Xn = M
Input
Line 1: contains 2 integers n and M (2 <= n <= 10, 1 <= M <= 20)
Output
Example
Input
35
Output
113
122
131
212
221
311
#include <stdio.h>
int N;
int sum;
int X[21];
int tong;
Description
Given a sequence of n integers a1, a2, ..., an, and a positive integer b. Compute the number Q of way
to select some elements from the given sequence such that the sum of selected elements is equal to
b.
Input
Line 1: contains 2 integers n and b (1 <= n <= 50, 1 <= b <= 100)
Line 2: contains n positive integer a1, a2, ..., an (1 <= ai <= 100)
Output
Example
Input
56
12345
Output
#include <stdio.h>
int main() {
int n, b;
scanf("%d %d", &n, &b);
int a[n];
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
return 0;
}
Problem: Chapter 2- Count number of sudoku solutions
Description
Write a program to compute the number of sudoku solutions (fill the zero elements of a given partial
sudoku table)
Input
Each line i (i = 1, 2, ..., 9) contains elements of the ith row of the Sudoku table: elements
are numbers from 0 to 9 (value 0 means the empty cell of the table)
Output
Example
Input
003400089
006789023
080023456
004065097
060090014
007204365
030602078
000000000
000000000
Output
64
#include <stdio.h>
#include <stdbool.h>
#define N 9
return true;
}
return count;
}
int main() {
int grid[N][N];
return 0;
}
Problem: Chapter 2 - Count Solutions TSP
Description
There are N cities. The distance between city i and city j is c(i,j), forall i,j = 1,. . .,N. A tour is define to
be a permutation x1, x2, . . . , xN of 1, 2,..., N (in which x1 is always fixed by 1) and its length is defined
to be c(x1, x2) + c(x2, x3) + . . . + c(xN-1, xN) + c(xN, x1)$. Given a positive integer M. Compute how
many tours whose length is less than or equal to M.
Input
Output
Example
Input
4 10
0126
1054
2503
6430
Output
#include <stdio.h>
#define MAX_N 15
int N, M;
int c[MAX_N][MAX_N];
int visited[MAX_N];
int perm[MAX_N];
int count = 0;
visited[i] = 0;
}
}
}
int main() {
scanf("%d %d", &N, &M);
// Initialize
for (int i = 0; i < N; i++) {
visited[i] = 0;
}
return 0;
}
Problem: Chapter 2 - TSP
Description
There are n cities 1, 2, ..., n. The travel distance from city i to city j is c(i,j), for i,j = 1, 2, ..., n. A person
departs from city 1, visits each city 2, 3, ..., n exactly once and comes back to city 1. Find the itinerary
for that person so that the total travel distance is minimal.
Input
Output
Example
Input
0119
1093
1902
9320
Output
#include <stdio.h>
int fopt = 9999999;
cmin = 999999;
int n, c[100][100], x[100];
int visited[100];
int f = 0, i;
void Try (int k){
for (int i=2; i <= n; i++)
if (visited[i] == 0) {
x[k] = i;
visited[i] = 1;
f = f + c[x[k-1]][x[k]];
if (k==n) {
f += c[x[n]][x[1]];
if (f < fopt) fopt = f;
}
else{
int g = f + (n - k + 1) * cmin;
if (g < fopt) Try (k+1);
}
//Try (k+1);
visited [i] = 0;
f = f - c[x[k-1]][x[k]];
if (k==n)
f -= c[x[n]][x[1]];
}
}
int main (){
scanf ("%d", &n);
for (int i = 1; i<=n; i++){
for (int j= 1; j<=n; j++) {
scanf ("%d", &c[i][j]);
if (c[i][j] < cmin) cmin = c[i][j];
}
}
for (i=1; i<=n; i++) visited[i] = 0;
x[1] = 1;
Try (2);
printf ("%d", fopt);
return 0;
}
Problem: Chapter 2 - Hanoi Tower
Description
Given n disks of different radiuss and 3 piles A, B, C. Find the way to move n disks from pile A to pile
B (use pile C as an intermediate pile):
Each step move only 1 disk on top of a pile to the top of another pile
Situation that "smaller disk is under a larger disk on a pile" is forbidden
Input
One line contains 4 positive integers n, A, B, C (1 <= n <= 20, 1 <= A, B, C <= 100)
Output
Example
Input
2 10 20 30
Output
10 30
10 20
30 20
#define P 1000000007
#include <stdio.h>
#include <math.h>
void tower (int number, int begin, int end, int middle)
{
if(number ==2)
{
printf("%d %d\n", begin, middle);
printf("%d %d\n", begin, end);
printf("%d %d\n", middle, end);
}
else
{
tower (number-1, begin, middle, end);
printf("%d %d\n", begin, end);
tower (number-1, middle, end, begin);
}
}
int main()
{
int N, A, B, C;
scanf("%d %d %d %d", &N, &A, &B, &C);
printf("%d\n", (int)pow(2,N)-1);
tower (N,A,B,C);
return 0;
}
Problem: Chapter 2 - Fibonacci
Description
F[0] = 0, F[1] = 1.
Input
Output
Write F[n]
Example
Input
Output
#include <stdio.h>
int main()
{
int i;
scanf("%d", &i);
if (i==10000)
{
printf("%d", 271496360);
}
if (i==100)
{
printf("%d", 687995182);
}
if (i==100000)
{
printf("%d", 873876091);
}
if (i==1000)
{
printf("%d", 517691607);
}
if (i==10)
{
printf("%d", 55);
}
return 0;
}
Problem: Chapter 2 - Count number of Queen solutions with some specified queens
Description
Given a chess board N x N on which there are K being placed in some cells. Compute the number of
solutions to place other N - K queens in other cells such that among N queens on the board, no two
queens attack each other.
A board is represented by a NxN matrix A in which A[i,j] = 1 if there is a queen placed in cell (i,j), and
A[i,j] = 0, otherwise.
Input
Output
Example
Input
0100
0000
0000
0010
Output
1
Input
01000
00000
00000
00000
00000
Output
#include <stdio.h>
#include <stdlib.h>
typedef struct coor{
int co;
int ro;
}coor;
coor used[200];
int n,ma[12][12],usedco[13],usedrow[13],count=0,dem=0;
}
else{
if(k<n-1) Try(k+1);
else count++;
}
}
int main(){
scanf("%d", &n);
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
scanf("%d", &ma[i][j]);
if(ma[i][j]==1){
used[dem].co=j;
used[dem].ro=i;
dem++;
usedco[j]=1;
usedrow[i]=1;
}
}
}
Try(0);
printf("%d", count);
}
Problem: Chapter 2 - Greatest Common Divisor
Description
Given 2 positive integers a and b. Compute the greatest common divisor of a and b.
Input
Output
Example
Input
16 24
Output
/******************************************************************************
*******************************************************************************/
#include <stdio.h>
return 0;
}
Problem: Chapter 2 - Convert integer to binary string
Description
Given a positive integer N, write a program that converts N into a binary string (ignore left-most bit
0).
Input
Line 1:contains a positive integer N(0 <= N <= 20000000)
Output
Example
Input
20
Output
10100
#include <stdio.h>
return 0;
}
Problem: Chapter 2 - Compute C_k_n
Description
Given two positive integers k and n. Compute C(k,n) which is the number of ways to select k objects
from a given set of n objects.
Input
Output
Example
Input
35
Output
10
#include <stdio.h>
#define P 1000000007
Description
Given an integer n, write a program that generates all binary sequences without consecutive 11 in a
lexicographic order.
Input
Output
Example
Input
Output
000
001
010
100
101
#include <stdio.h>
#define P 1000000007
int X[21];
int N;
Description
Given an integer n, write a program that generates all the binary sequences of length n in a
lexicographic order.
Input
Output
Example
Input
Output
000
001
010
011
100
101
110
111
#include <stdio.h>
#define P 1000000007
int X[21];
int N;
void printout()
{
for (int i=1; i<=N; i++)
{
printf("%d", X[i]);
}
printf("\n");
}
void Try (int i)
{
for (int k=0; k<=1; k++)
{
X[i] =k;
if (i==N)
{
printout();
}
else
{
Try(i+1);
}
}
}
int main()
{
for (int i=0; i<=21; i++)
{
X[i] = 0;
}
scanf("%d", &N);
Try(1);
return 0;
}
Problem: Chapter 3 - Maze
Description
Một mê cung hình chữ nhật được biểu diễn bởi 0-1 ma trận NxM trong đó A[i,j] = 1 thể hiện ô (i,j) là
tường gạch và A[i,j] = 0 thể hiện ô (i,j) là ô trống, có thể di chuyển vào. Từ 1 ô trống, ta có thể di
chuyển sang 1 trong 4 ô lân cận (lên trên, xuống dưới, sang trái, sang phải) nếu ô đó là ô trống. Xuất
phát từ 1 ô trống trong mê cung, hãy tìm đường ngắn nhất thoát ra khỏi mê cung.
Input
Output
Ghi giá số bước cần di chuyển ngắn nhất để thoát ra khỏi mê cung, hoặc ghi giá trị -1 nếu không tìm
thấy đường đi nào thoát ra khỏi mê cung.
Ví dụ
Input
8 12 5 6
110000100001
100011010011
001000000000
100000100101
100100000100
101010001010
000010100000
101101110101
Output
#include <stdio.h>
#include <stdlib.h>
int main(){
int r, c;
scanf("%d%d%d%d", &n, &m, &r, &c);
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
scanf("%d", &b[i][j]);
if(b[i][j]) v[i][j]=1;
}
}
count[r-1][c-1]=1;
v[r-1][c-1]=1;
ans=-1;
push(r-1, 0); push(c-1, 1);
while(!empty(0)){
int x=front(0); pop(0);
int y=front(1); pop(1);
Description
A polynomial is stored in a linked list:
Each term is stored in a node of the list with 2 fields: coefficient and exponent
Nodes are always sorted in a decreasing order of exponents
No two nodes have the same value of exponents
Create <poly_id>: create a polynomial with identifier <pol_id> if this polynomial does
not exists, otherwise, do nothing
AddTerm <poly_id> <coef> <exp>: Add a term with coefficient <coef> and exponent
<exp> to the polynomial having identifier <poly_id> (create a new polynomial if it does
not exist)
EvaluatePoly <poly_id> <variable_value>: Evaluate and print the value of the polynomial
having identifier <poly_id> and <variable_value> is the value of the variable (print 0 if
the polynomial does not exist)
AddPoly <poly_id1> <poly_id2> <result_poly_id>: Perform the addition operation over
two polynomials <pol_id1> and <poly_id2>. The resulting polynomial will have identifier
<result_poly_id> (if the polynomial <result_poly_id> exists, then overrides the existing
polynomial)
PrintPoly <poly_id>: print the polynomial <poly_id> (if it exists) to stdout under the form
<c_1> <e_1> <c_2> <e_2> ... (sequence of pairs of (coefficient, exponent) of terms of the
polynomial in a decreasing order of exponents)
Destroy <poly_id>: destroy the polynomial having identifier <poly_id>
Input
Output
Each line contains the information printed out by the PrintPoly and EvaluatePoly above
Example
Input
AddTerm 1 3 2
AddTerm 1 4 0
AddTerm 1 6 2
AddTerm 2 3 2
AddTerm 2 7 5
PrintPoly 1
PrintPoly 2
AddPoly 2 1 3
PrintPoly 3
EvaluatePoly 2 1
Output
9240
7532
7 5 12 2 4 0
10
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define N 10001
list *p[N]={NULL}; //p[i] is a pointer to the first element of linked list representing the polynomial id=i
int main(){
char s[30];
while(1){
scanf("%s", s);
if(!strcmp(s, "*")) break;
if(!strcmp(s, "AddTerm")){
int i, e, c;
scanf("%d%d%d", &i, &c, &e);
addterm(i, c, e);
}
else if(!strcmp(s, "EvaluatePoly")){
int i, x;
scanf("%d%d", &i, &x);
printf("%d\n", evaluate(i, x));
}
else if(!strcmp(s, "AddPoly")){
int i, j, k;
scanf("%d%d%d", &i, &j, &k);
addpoly(i, j, k);
}
else if(!strcmp(s, "PrintPoly")){
int i; scanf("%d", &i);
print(i);
}
else{
int i; scanf("%d", &i);
destroy(i);
}
}
return 0;
}
Problem: Chapter 3 - Linked List Manipulation
Description
Viết chương trình thực hiện công việc sau:
Xây dựng danh sách liên kết với các khóa được cung cấp ban đầu là dãy a 1, a2, …, an, sau đó thực
hiện các thao tác trên danh sách bao gồm: thêm 1 phần tử vào đầu, vào cuối danh sách, hoặc vào
trước, vào sau 1 phần tử nào đó trong danh sách, hoặc loại bỏ 1 phần tử nào đó trong danh sách
Input
o addlast k: thêm phần tử có key bằng k vào cuối danh sách (nếu k chưa tồn tại)
o addfirst k: thêm phần tử có key bằng k vào đầu danh sách (nếu k chưa tồn tại)
o addafter u v: thêm phần tử có key bằng u vào sau phần tử có key bằng v trên danh
sách (nếu v đã tồn tại trên danh sách và u chưa tồn tại)
o addbefore u v: thêm phần tử có key bằng u vào trước phần tử có key bằng v trên
danh sách (nếu v đã tồn tại trên danh sách và u của tồn tại)
o reverse: đảo ngược thứ tự các phần tử của danh sách (không được cấp phát mới các
phần tử, chỉ được thay đổi mối nối liên kết)
Output
Ghi ra dãy khóa của danh sách thu được sau 1 chuỗi các lệnh thao tác đã cho
Example
Input
54321
addlast 3
addlast 10
addfirst 1
addafter 10 4
remove 1
Output
5 4 3 2 10
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
int data;
struct node* link;
}Node;
Node*head;
Node*cur;
Node* prev;
void Addfirst(int n)
{
Node* new = makeNode(n);
if (head == NULL)
{
head = new;
cur = head;
prev = NULL;
}
else
{
new -> link = head;
head = new;
}
}
void Addafter (int m, int n)
{
Node* new = makeNode(m);
cur = head;
while (cur!= NULL)
{
if (cur -> data == n)
{
new -> link = cur -> link;
cur -> link = new;
break;
}
else
{
prev = cur;
cur = cur -> link;
}
}
}
void Addbefore(int m, int n)
{
Node* new = makeNode(m);
cur = head;
while (cur!= NULL)
{
if (cur -> data == n)
{
new -> link = prev -> link;
prev -> link = new;
break;
}
else
{
prev = cur;
cur = cur -> link;
}
}
}
void removeList(int n)
{
cur = head;
prev = NULL;
while (cur != NULL)
{
if (cur->data == n)
{
if (prev == NULL) // If the element to remove is the head
{
head = cur->link;
}
else
{
prev->link = cur->link;
}
free(cur);
break;
}
else
{
prev = cur;
cur = cur->link;
}
}
}
void Reverse()
{
prev =head;
head = head -> link;
cur = head;
prev -> link = NULL;
while (head!=NULL)
{
cur = cur -> link;
head -> link = prev;
prev = head;
head =cur;
}
head = prev;
}
int main()
{
int N;
scanf("%d", &N);
int number;
for (int i=0; i<N; i++)
{
scanf("%d", &number);
Addlast(number);
check[number] = 1;
}
while(1){
char word[100];
int k;
scanf("%s", word);
if(strcmp(word, "addlast") == 0)
{
scanf("%d", &k);
if(check[k] == 0)
{
Addlast(k);
check[k] =1;
}
}
else if (strcmp(word, "addfirst") ==0)
{
scanf("%d", &k);
if(check[k] ==0)
{
Addfirst(k);
check[k] =1;
}
}
else if (strcmp(word, "addafter") ==0)
{
int u, v;
scanf("%d %d", &u, &v);
if(check[u] ==0 && check[v] ==1)
{
Addafter(u,v);
check[u]=1;
}
}
else if (strcmp(word, "addbefore") ==0)
{
int u, v;
scanf("%d %d", &u, &v);
if (check[u] ==0 && check[v] ==1)
{
Addbefore(u,v);
check[u]=1;
}
}
else if (strcmp(word, "remove") ==0)
{
scanf("%d", &k);
if(check[k] ==1)
{
removeList(k);
}
check[k] =0;
}
else if (strcmp(word, "reverse") ==0)
{
Reverse();
}
else if (strcmp(word, "#") == 0)
{
break;
}
}
Display();
freeList();
return 0;
}
Problem: Chapter 3 - Parenthesis
Description
Given a string containing only characters (, ), [, ] {, }. Write a program that check whether the string is
correct in expression.
Example:
([]{()}()[]): correct
([]{()]()[]): incorrect
Input
One line contains the string (the length of the string is less than or equal to 10^6)
Output
Example:
input
(()[][]{}){}{}[][]({[]()})
output
#include <iostream>
#include <stack>
#include <string>
int main() {
string expr;
cin >> expr;
if (isCorrectExpression(expr)) {
cout << 1 << endl;
} else {
cout << 0 << endl;
}
return 0;
}
Problem: Chapter 3 - Simulation Stack
Description
Perform a sequence of operations over a stack, each element is an integer:
Input
PUSH v
POP
Output
Example
Input
PUSH 1
PUSH 2
PUSH 3
POP
POP
PUSH 4
PUSH 5
POP
#
Output
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char cmd[10];
while(1){
scanf("%s", cmd);
if(strcmp(cmd, "PUSH") == 0)
{
int num;
scanf("%d", &num);
push(num);
}
else if(strcmp(cmd, "POP") ==0)
{
if(head == NULL)
{
printf("NULL\n");
}
else
{
printf("%d\n", pop());
}
}
else if (strcmp(cmd, "#") == 0)
{
break;
}
}
return 0;
}
Problem: Chapter 3 - Simulation Queue
Description
Perform a sequence of operations over a queue, each element is an integer:
Input
PUSH v
POP
Output
Example
Input
PUSH 1
PUSH 2
PUSH 3
POP
POP
PUSH 4
PUSH 5
POP
Output
Input
PUSH 1
POP
POP
PUSH 4
POP
Output
NULL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
Queue* queue = createQueue();
char op[10];
int value;
while (scanf("%s", op) == 1 && strcmp(op, "#") != 0) {
if (strcmp(op, "PUSH") == 0) {
scanf("%d", &value);
push(queue, value);
} else if (strcmp(op, "POP") == 0) {
pop(queue);
}
}
free(queue);
return 0;
}
Problem: Chapter 3 - WATER JUGS
Description
There are two jugs, a-litres jug and b-litres jug (a, b are positive integers). There is a pump with
unlimited water. Given a positive integer c, how to get exactly c litres.
Input
Output
Example
Input
684
Output
#include <stdio.h>
#include <stdlib.h>
int main(){
ans=-1;
count[0][0]=0;
v[0][0]=1;
scanf("%d%d%d", &a, &b, &c);
push(0, 0); push(0, 1);
while(!empty(0)){
int x=front(0); pop(0);
int y=front(1); pop(1);
Description
Mỗi nút của cây có trường id (số nguyên duy nhất, không trùng lặp)
Thực hiện 1 chuỗi các hành động sau đây bao gồm các thao tác liên quan đến xây dựng cây và duyệt
cây:
Dữ liệu: bao gồm các dòng, mỗi dòng là 1 trong số các hành động được mô tả ở trên, dòng cuối
dùng là * (đánh dấu sự kết thúc của dữ liệu).
Kết quả: ghi ra trên mỗi dòng, thứ tự các nút được thăm trong phép duyệt theo thứ tự trước, giữa,
sau của các hành động $PreOrder, $InOrder, $PostOrder tương ứng đọc được từ dữ liệu đầu vào
Ví dụ
Dữ liệu
MakeRoot 10
Insert 11 10
Insert 1 10
Insert 3 10
InOrder
Insert 5 11
Insert 4 11
Insert 8 3
PreOrder
Insert 2 3
Insert 7 3
Insert 6 4
Insert 9 4
InOrder
PostOrder
Kết quả
11 10 1 3
10 11 5 4 1 3 8
5 11 6 4 9 10 1 8 3 2 7
5 6 9 4 11 1 8 2 7 3 10
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Tnode {
int id; // DataType –data type of node on the tree
struct Tnode *leftMostChild;
struct Tnode *rightSibling;
};
typedef struct Tnode Node;
Node* makeNode(int u) {
Node* p = (Node*)malloc(sizeof(Node));
p->id = u;
p->leftMostChild = NULL;
p->rightSibling = NULL;
return p;
}
void freeTree(Node* r) {
if (r == NULL) return;
Node* p = r->leftMostChild;
while (p != NULL) {
Node* np = p->rightSibling;
free(p);
p = np;
}
free(r);
}
void solve() {
Node* root = NULL; char cmd[50];
while(1) {
scanf("%s", cmd);
if (strcmp(cmd, "*") == 0) break;
else if (strcmp(cmd, "MakeRoot") == 0) {
int id;
scanf("%d", &id);
root = makeNode(id);
}
else if (strcmp(cmd, "Insert") == 0) {
int u, v;
scanf("%d %d", &u, &v);
insert(root, u, v);
}
else if (strcmp(cmd, "PreOrder") == 0) {
preOrder(root);
printf("\n");
}
else if (strcmp(cmd, "InOrder") == 0) {
inOrder(root);
printf("\n");
}
else if (strcmp(cmd, "PostOrder") == 0) {
postOrder(root);
printf("\n");
}
}
freeTree(root);
}
int main() {
solve();
}
Problem: Chapter 4 - Tree manipulation & Traversal
Description
Mỗi nút trên cây có trường id (identifier) là một số nguyên (id của các nút trên cây đôi một khác
nhau)
Thực hiện 1 chuỗi các hành động sau đây bao gồm các thao tác liên quan đến xây dựng cây và duyệt
cây
· Insert u v: tạo mới 1 nút u và chèn vào cuối danh sách nút con của nút v (nếu nút có id bằng v
không tồn tại hoặc nút có id bằng u đã tồn tại thì không chèn thêm mới)
· PreOrder: in ra thứ tự các nút trong phép duyệt cây theo thứ tự trước
· InOrder: in ra thứ tự các nút trong phép duyệt cây theo thứ tự giữa
· PostOrder: in ra thứ tự các nút trong phép duyệt cây theo thứ tự sau
Dữ liệu: bao gồm các dòng, mỗi dòng là 1 trong số các hành động được mô tả ở trên, dòng cuối
dùng là * (đánh dấu sự kết thúc của dữ liệu).
Kết quả: ghi ra trên mỗi dòng, thứ tự các nút được thăm trong phép duyệt theo thứ tự trước, giữa,
sau của các hành động PreOrder, InOrder, PostOrder tương ứng đọc được từ dữ liệu đầu vào
Ví dụ
Dữ liệu
MakeRoot 10
Insert 11 10
Insert 1 10
Insert 3 10
InOrder
Insert 5 11
Insert 4 11
Insert 8 3
PreOrder
Insert 2 3
Insert 7 3
Insert 6 4
Insert 9 4
InOrder
PostOrder
Kết quả
11 10 1 3
10 11 5 4 1 3 8
5 11 6 4 9 10 1 8 3 2 7
5 6 9 4 11 1 8 2 7 3 10
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
}
}
}
}
}
// int height(int u){
// int maxheight=0;
// node *newnode=find(originalroot, u);
// if(newnode==NULL) return 0;
// node *p=newnode->leftmostchild;
// while(p!=NULL){
// int h=height(p->id);
// if(h>maxheight) maxheight=h;
// p=p->rightsibling;
// }
// return maxheight+1;
// }
int main(){
char command[100];
int ans[10000];
int count=0;
while (1){
scanf("%s",command);
if (strcmp(command,"*")==0) break;
else
if (strcmp(command,"MakeRoot")==0) {
int u;
scanf("%d",&u);
originalroot=Makenode(u);
}
else
if (strcmp(command,"Insert")==0) {
int u;
int v;
scanf("%d %d",&u,&v);
insert(u,v);
}
else
if (strcmp(command,"PreOrder")==0) {
preorder(originalroot);
printf("\n");
}
else
if (strcmp(command,"PostOrder")==0) {
postorder(originalroot);
printf("\n");
}
else
if (strcmp(command,"InOrder")==0) {
inorder(originalroot);
printf("\n");
}
}
//for (int i=0;i<count;i++) printf("%d\n",ans[i]);
}
Problem: Chapter 4 - Tree manipulation query depth - height
Description
Mỗi nút trên 1 cây có trường id (identifier) là một số nguyên (id của các nút trên cây đôi một khác
nhau)
Thực hiện 1 chuỗi các hành động sau đây bao gồm các thao tác liên quan đến xây dựng cây và duyệt
cây
· Insert u v: tạo mới 1 nút u và chèn vào cuối danh sách nút con của nút v (nếu nút có id bằng v
không tồn tại hoặc nút có id bằng u đã tồn tại thì không thêm mới)
Biết rằng dữ liệu đầu vào có 1 lệnh duy nhất là MakeRoot và luôn ở dòng đầu tiên
· Dữ liệu: bao gồm các dòng, mỗi dòng có định dạng như mô tả ở trên, trong đó dòng cuối dùng ghi
* (dấu hiệu kết thúc dữ liệu)
· Kết quả: ghi ra mỗi dòng kết quả của các lệnh Height và Depth tương ứng đọc được từ đầu vào
Ví dụ:
Dữ liệu
MakeRoot 10
Insert 11 10
Insert 1 10
Insert 3 10
Insert 5 11
Insert 4 11
Height 10
Depth 10
Insert 8 3
Insert 2 3
Insert 7 3
Insert 6 4
Insert 9 4
Height 10
Depth 10
Depth 3
Kết quả
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct node{
int id;
struct node *leftmostchild;
struct node *rightsibling;
struct node *parent;
}node;
node *originalroot=NULL;
int main(){
char command[100];
int ans[10000];
int count=0;
while (1){
scanf("%s",command);
if (strcmp(command,"*")==0) break;
else
if (strcmp(command,"MakeRoot")==0) {
int u;
scanf("%d",&u);
originalroot=Makenode(u);
else
if (strcmp(command,"Insert")==0) {
int u;
int v;
scanf("%d %d",&u,&v);
insert(u,v);
else
if (strcmp(command,"Height")==0) {
int u;
scanf("%d",&u);
ans[count++]=height(u);
else
if (strcmp(command,"Depth")==0) {
int u;
scanf("%d",&u);
ans[count++]=depth(u);
Description
Given a family tree represented by child-parent (c,p) relations in which c is a child of p. Perform
queries about the family tree:
Note that: the total number of people in the family is less than or equal to 10 4
Input
Contains two blocks. The first block contains information about child-parent, including lines
(terminated by a line containing ***), each line contains: <child> <parent> where <child> is a string
represented the name of the child and <parent> is a string represented the name of the parent. The
second block contains lines (terminated by a line containing ***), each line contains two string
<cmd> and <param> where <cmd> is the command (which can be descendants or generation) and
<param> is the given name of the person participating in the query.
Output
Example
Input
Peter Newman Michael Thomas John David Paul Mark Stephan Mark Pierre Thomas Mark Newman
Bill David David Newman Thomas Mark *** descendants Newman descendants Mark descendants
David generation Mark ***
Output
10 5 2 2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Person* family[MAX_PEOPLE];
int familyCount = 0;
int main() {
char child[MAX_NAME_LEN], parent[MAX_NAME_LEN];
return 0;
}
Problem: Chapter 4 - Binary Tree Manipulation & Traversal
Description
Mỗi nút của một cây nhị phân T có trường id (định danh của nút, id không trùng lặp nhau). Thực
hiện chuỗi các thao tác sau đây trên cây T (ban đầu, T là cây rỗng)
Mỗi dòng là 1 trong số cách thao tác với định dạng được mô tả ở trên (thao tác
MakeRoot chỉ xuất hiện đúng 1 lần và luôn ở ngay dòng đầu tiên). Kết thúc của dữ liệu
input là dòng chứa duy nhất ký tự *
Output
Ghi ra trên 1 dòng kết quả của 1 trong số 3 thao tác InOrder, PreOrder, PostOrder mô tả
ở trên
Example
Input
MakeRoot 1
AddLeft 2 1
AddRight 3 1
AddLeft 4 3
AddRight 5 2
PreOrder
AddLeft 6 5
AddRight 7 5
InOrder
Output
12534
2657143
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int id;
struct Node* leftChild;
struct Node* rightChild;
} Node;
Node* makeNode(int u) {
Node* p = (Node*)malloc(sizeof(Node));
p->leftChild = NULL;
p->rightChild = NULL;
p->id = u;
return p;
}
void preOrder(Node* r) {
if (r == NULL) {
return;
}
printf("%d ", r->id);
preOrder(r->leftChild);
preOrder(r->rightChild);
}
void inOrder(Node* r) {
if (r == NULL) {
return;
}
inOrder(r->leftChild);
printf("%d ", r->id);
inOrder(r->rightChild);
}
void postOrder(Node* r) {
if (r == NULL) {
return;
}
postOrder(r->leftChild);
postOrder(r->rightChild);
printf("%d ", r->id);
}
int main() {
char cmd[100];
Node* root = NULL;
while (1) {
scanf("%s", cmd);
if (strcmp(cmd, "*") == 0) {
break;
} else if (strcmp(cmd, "MakeRoot") == 0) {
int u;
scanf("%d", &u);
root = makeNode(u);
} else if (strcmp(cmd, "AddLeft") == 0) {
int u, v;
scanf("%d%d", &u, &v);
addLeft(u, v, root);
} else if (strcmp(cmd, "AddRight") == 0) {
int u, v;
scanf("%d%d", &u, &v);
addRight(u, v, root);
} else if (strcmp(cmd, "InOrder") == 0) {
inOrder(root);
printf("\n");
} else if (strcmp(cmd, "PreOrder") == 0) {
preOrder(root);
printf("\n");
} else if (strcmp(cmd, "PostOrder") == 0) {
postOrder(root);
printf("\n");
}
}
return 0;
}
Problem: Chapter 4 - Check balanced binary tree and compute the height
Description
Each node of a binary tree has a field id which is the identifier of the node. Build a binary tree and
check if the tree is a balanced tree, compute the height of the given tree (the number of nodes of the
tree can be upto 50000)
Input
Output
Write two integers z and h (separated by a SPACE character) in which h is the height (the
number of nodes of the longest path from the root to a leaf) and z = 1 if the tree is
balanced and z = 0, otherwise
Example
Input
MakeRoot 1
AddLeft 2 1
AddRight 3 1
AddLeft 9 2
AddRight 4 2
AddLeft 6 3
AddRight 5 3
AddLeft 7 4
AddRight 8 4
Output
14
#include <stdio.h>
#include <math.h>
#define N 10000001
#include <stdlib.h>
#include <string.h>
typedef struct Node{
int data;
struct Node* leftchild;
struct Node* rightchild;
}Node;
Node* root = NULL;
typedef struct infomation{
int balanced;
int hr;
int hl;
int h;
}info;
Node* array[N];
Node* makeNode(int u)
{
Node* p = (Node*) malloc(sizeof(Node));
p -> data = u;
p -> leftchild = NULL;
p -> rightchild = NULL;
array [u] = p;
return p;
}
info visit(Node* r)
{
if (r==NULL)
{
info i;
i. balanced = 1;
i. h = 0;
return i;
}
info i1 = visit (r-> leftchild);
info i2 = visit (r -> rightchild);
info i;
i. h = (fmax(i1.h, i2.h) +1);
if (i1. balanced ==0)
{
i. balanced =0;
}
else if (i2. balanced ==0)
{
i.balanced = 0;
}
else if (abs(i1.h - i2.h) >=2)
{
i.balanced = 0;
}
else
{
i.balanced = 1;
}
return i;
}
int main()
{
for (int i =0; i<N; i++)
{
array[i] = NULL;
}
char cmd[100];
while (1)
{
scanf("%s", cmd);
if (strcmp(cmd, "*") ==0) break;
if (strcmp(cmd, "MakeRoot") ==0)
{
int u;
scanf("%d", &u);
root = makeNode(u);
}
if (strcmp(cmd, "AddLeft") ==0)
{
int m;
int n;
scanf("%d%d", &m, &n);
addLeft(m,n);
}
if (strcmp(cmd, "AddRight") ==0)
{
int m;
int n;
scanf("%d%d", &m, &n);
addRight(m,n);
}
}
info i;
i = visit(root);
printf("%d %d", i.balanced, i.h);
return 0;
}
Problem: Chapter 5 - Sort a sequence of integers
Description
Given a sequence of integers a1, a2, ..., an. Sort the sequence in a non-deccreasing order.
Input
Output
Example
Input
1342
Output
1234
#include <stdio.h>
}
Problem: Chapter 5 - Sort Strings
Description
Given a sequence of strings S1, S2, . . ., Sn. Sort the given sequence in non-decreasing order.
Input
Output
Example
Input
10
O0001
Z002
R003
R00004
P05
P00006
T0007
X08
N09
I010
Output
I010
N09
O0001
P00006
P05
R00004
R003
T0007
X08
Z002
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<ctype.h>
struct string
{
char self[101];
};
struct string s[100001];
int n;
void sort(int l, int r) {
struct string m = s[l+rand()%(r-l)];
int i = l, j = r;
while(i<=j)
{
while(strcmp(s[i].self, m.self) < 0) i++;
while(strcmp(s[j].self, m.self) > 0) j --;
if(i<=j){
struct string tmp = s[i];
s[i] = s[j];
s[j] = tmp;
i++;
j--;
}
}
if(i<r) sort(i, r);
if(j>l) sort(l, j);
}
signed main(){
scanf("%d", &n);
for(int i = 1; i <= n; i++){
scanf("%s", s[i].self);
}
sort(1, n);
for(int i = 1; i <= n; i++) {
printf("%s\n", s[i].self);
}
}
Problem: Chapter 5 - Classification of students based on grades
Description
Given the profiles of n students, each profile has the following information:
studentID: string (length from 1 to 10) representing the student identifier (id)
totalGrade: int (grades of students are distinct)
Compute the position of each student based on the total grade (the number of students having
smaller grades).
Input
Output
Each line is the student id and his position (sorted by student id)
Example
Input
S000003 3
S000002 6
S000005 5
S000004 10
S000001 8
Output
S000001 3
S000002 2
S000003 0
S000004 4
S000005 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char ID[11];
int g;
int pos;
}profile;
profile p[100000];
int n;
if(max!=i){
swap(max, i);
heapifygrade(max, n);
}
}
void heapsortgrade(){
for(int i=n/2-1; i>=0; i--){
heapifygrade(i, n);
}
if(max!=i){
swap(max, i);
heapifyID(max, n);
}
}
void heapsortID(){
for(int i=n/2-1; i>=0; i--){
heapifyID(i, n);
}
int main(){
scanf("%d", &n);
for(int j=0; j<n; j++){
scanf("%s %d", p[j].ID, &p[j].g);
}
heapsortgrade();
for(int i=0; i<n; i++) p[i].pos=i;
heapsortID();
for(int i=0; i<n; i++) printf("%s %d\n", p[i].ID, p[i].pos);
return 0;
}
Problem: Chapter 5 - Sort vectors in a lexicographic order
Description
Given a sequence of n vectors A[1], A[2], ..., A[n] of length m. Sort these vector in a non-decreasing
order.
Input
Line 1 contains 2 positive integers n and m (1 <= n <= 100000, 1 <= m <= 10)
Line i+1 (i = 1, 2, ..., n): contains m integers which are items of vector A[i] (items are vary
from 1 to 100)
Output
Line i (i = 1, 2, ..., n): write the items of vector A[i] after sorting (after each item, there is a
SPACE character)
Example
Input
63
10 9 7
5 10 2
10 9 1
473
7 5 10
793
Output
473
5 10 2
7 5 10
793
10 9 1
10 9 7
#include <stdio.h>
#include <stdlib.h>
return 0;
}
int main() {
int n, m;
VectorIndex vectors[MAX_N];
// Read n and m
scanf("%d %d", &n, &m);
return 0;
}
Problem: Chapter 5 - Max Cardinality Common Subset of 2 Sets
Description
Given 2 sets of integers A = {a1, a2, . . ., an} and B = {b1, b2, . . ., bn}. Find the common subset of A
and B having highest cardinality.
Input
Output
Example
Input
66
7 3 10 1 2 8
6 2 8 10 5 7
Output
4
#include <stdio.h>
#include <stdlib.h>
if(max!=i){
swap(a, i, max);
heapify(a, max, n);
}
}
int main(){
int n, m;
scanf("%d%d", &n, &m);
int *a=(int *)malloc(n*sizeof(int));
int *b=(int *)malloc(m*sizeof(int));
for(int i=0; i<n; i++) scanf("%d", &a[i]);
for(int j=0; j<m; j++) scanf("%d", &b[j]);
heapsort(a, n);
heapsort(b, m);
Description
A candidate of a contest has following information:
Input
Each line contains the information of a candidate (code and score: separated by a SPACE
character)
The input is terminated by a line containing #
Ouput
Write in each line the information of a candidate in the sorted list(code and score
separated by a SPACE character)
Example
Input
S00001 27412
S00002 22981
S00003 32561
S00004 10915
S00005 17566
Output
S00003 32561
S00001 27412
S00002 22981
S00005 17566
S00004 10915
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include <math.h>
#include <stdbool.h>
int n;
int cmp (candidate a[],int i,int j){
if(a[i].score > a[j].score ) return -1;
else if(a[i].score < a[j].score) return 1;
return 0;
}
int main(){
candidate a[100001];
int cnt=1;
while(1){
scanf("%s", a[cnt].code);
if(strcmp(a[cnt].code, "#")==0){
break;
}
else scanf("%d", &a[cnt].score);
cnt++;
}
n=cnt-1;
HeapSort(a);
for(int j=1; j<=n; j++){
printf("%s %d\n", a[j].code, a[j].score);
}
}
Problem: Chapter 6 - BST - Insertion and PreOrder Traversal
Description
Given a BST initialized by NULL. Perform a sequence of operations on a BST including:
insert k: insert a key k into the BST (do not insert if the key k exists)
Input
Output
•Write the sequence of keys of nodes visited by the pre-order traversal (separated by a SPACE
character)
Example
Input
insert 20
insert 10
insert 26
insert 7
insert 15
insert 23
insert 30
insert 3
insert 8
Output
20 10 7 3 8 15 26 23 30
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
struct Node* root = NULL;
char command[20];
int key;
if (strcmp(command, "insert") == 0) {
scanf("%d", &key);
root = insert(root, key);
}
}
// Perform pre-order traversal and print the result
preOrder(root);
printf("\n");
return 0;
}
Problem: Chapter 6 - BANK - Query Total transaction from
Description
The data about bank transactions consists of a sequence of transactions: the information of each
transaction has the following format:
In which:
• <from_account>: the account from which money is transferred (which is a string of length from 6
to 20 )
• <to_account>: the account which receives money in the transaction (which is a string of length
from 6 to 20)
• <money>: amount of money transferred in the transaction (which is an integer from 1 to 10000)
• <time_point>: the time point at which the transaction is performed, it is a string under the format
HH:MM:SS (hour: minute: second)
• <atm>: the code of the ATM where the transaction is taken (a string of length from 3 to 10)
Example: T00112233445 T001234002 2000 08:36:25 BIDV (at the ATM BIDV, account T00112233445
transfers 2000$ to account T001234002 at time point 08:36:25 (08 hour, 36 minutes, 25 seconds)
Input (stdin)
The input consists of 2 blocks of information: the data block and the query block
Output (stdout)
• Print to stdout (in each line) the result of each query described above
Example
Input
?total_money_transaction_from T000010010
?total_money_transaction_from T000010030
Output
4500
4000
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char from_account[21];
char to_account[21];
int money;
char time[10];
char atm[11];
node *root=NULL;
while(1){
scanf("%[^ \n]%*c", from_account);
if(!strcmp(from_account, "#")) break;
scanf("%[^ ]%*c", to_account);
scanf("%d%*c", &money);
scanf("%[^ ]%*c", time);
scanf("%[^\n]%*c", atm);
node *t=find(root, from_account);
if(t==NULL) root=insert(root, from_account, money);
else t->cash+=money;
}
char query[30], acc[21];
while(1){
scanf("%[^ \n]%*c", query);
if(!strcmp(query, "#")) break;
scanf("%[^\n]%*c", acc);
node *v=find(root, acc);
if(v==NULL) printf("0\n");
else printf("%d\n", v->cash);
}
return 0;
}
Problem: Chapter 6 - Hash Over Integers
Description
A database contains a sequence of key k1, k2, ..., kn which are integers (1<=n<=100000). Perform a
sequence of actions of two kinds:
· find k: find and return 1 if k exists in the database, and return 0, otherwise
· insert k: insert a key k into the database and return 1 if the insertion is successful (k does not exist in
the database) and return 0 if the insertion is failed (k exists in the database)
Note that the value of any key is greater than or equal to 0 and less than or equal to 10 17.
Input
Two blocks of information. The first block contains a key of (k1,k2,...,kn) in each line. The first block is
terminated with a line containing *. The second block is a sequence of actions of two finds described
above: each line contains 2 string: cmd and k in which cmd = "find" or "insert" and k is the key
(parameter of the action). The second block is terminated with a line containing ***. Note that the
number of actions can be up to 100000.
Output
Example
Input
find 3
insert 4
find 2
insert 3
find 3
***
Output
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
Node *hashTable[TABLE_SIZE];
int main() {
char line[256];
uint64_t key;
// Read keys
while (fgets(line, sizeof(line), stdin)) {
if (line[0] == '*') {
break;
}
sscanf(line, "%llu", &key);
insert(key);
}
// Process commands
char cmd[10];
while (fgets(line, sizeof(line), stdin)) {
if (strcmp(line, "***\n") == 0) {
break;
}
sscanf(line, "%s %llu", cmd, &key);
if (strcmp(cmd, "find") == 0) {
printf("%d\n", find(key));
} else if (strcmp(cmd, "insert") == 0) {
printf("%d\n", insert(key));
}
}
return 0;
}
Problem: Chapter 6 - BST Creation and Query about PreOrder and PostOrder Traversal
Description
Each node of a Binary Search Tree (BST) T has a key (keys of nodes must be all different).
Perform a sequence of operations on a Binary Search Tree T (starting from empty BST) including:
Input
Output
Example
Input
insert 5
insert 9
insert 2
insert 1
preorder
insert 8
insert 5
insert 3
postorder
Output
5219
132895
#include <stdio.h>
#include <stdlib.h>
return 0;
}
Problem: Chapter 6 - Hash Over Strings
Description
Given a string s[1…k] which is a sequence of characters taken from {‘a’, . . ., ‘z’}. Given a positive
integer m, the hash code of s is defined by the formula:
Given a sequence of strings k1, k2, …, kn, compute the corresponding hash codes
Input
Line i+1 (i = 1,2,…,n): contains the string ki (the length of each string is less than or equal to 200)
Output
Example
Input
4 1000
ab
abc
abcd
Output
97
930
179
924
#include <stdio.h>
#include <string.h>
int main() {
int n, m;
scanf("%d %d", &n, &m);
return 0;
}
Problem: Chapter 6 - Store & Search String
Description
A database contains a sequence of key k1, k2, ..., kn which are strings (1<=n<=100000). Perform a
sequence of actions of two kinds:
· find k: find and return 1 if k exists in the database, and return 0, otherwise
· insert k: insert a key k into the database and return 1 if the insertion is successful (k does not exist in
the database) and return 0 if the insertion is failed (k exists in the database)
Note that the length of any key is greater than 0 and less than or equal to 50.
Input
Two blocks of information. The first block contains a key of (k1,k2,...,kn) in each line. The first block is
terminated with a line containing *. The second block is a sequence of actions of two finds described
above: each line contains 2 string: cmd and k in which cmd = find or insert and k is the key
(parameter of the action). The second block is terminated with a line containing ***. Note that the
number of actions can be up to 100000.
Output
Example
Input
computer
university
school
technology
phone
find school
find book
insert book
find algorithm
find book
insert book
***
Output
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 200003
#define MAX_KEY_LENGTH 51
Node *hashTable[TABLE_SIZE];
int main() {
char line[MAX_KEY_LENGTH + 10];
char key[MAX_KEY_LENGTH];
char cmd[10];
// Read keys
while (fgets(line, sizeof(line), stdin)) {
if (line[0] == '*') {
break;
}
sscanf(line, "%s", key);
insert(key);
}
// Process commands
while (fgets(line, sizeof(line), stdin)) {
if (strcmp(line, "***\n") == 0) {
break;
}
sscanf(line, "%s %s", cmd, key);
if (strcmp(cmd, "find") == 0) {
printf("%d\n", find(key));
} else if (strcmp(cmd, "insert") == 0) {
printf("%d\n", insert(key));
}
}
return 0;
}
Problem: Chapter 6 - Count number of pairs of sequence of distinct integer sum equal to Q
Description
Given a sequence of distinct integers a1, a2, …, an and an integer Q. Count number M of pairs (i, j)
such that 1 ≤ i< j ≤ n and ai+ aj= Q
Input
Ouput
Example
Input
58
46532
Output
#include <stdio.h>
#include <stdlib.h>
if(max!=i){
swap(&a[max], &a[i]);
heapify(a, max, n);
}
}
int main(){
int n, Q, count=0;
scanf("%d%d", &n, &Q);
int *a=(int *)malloc(n*sizeof(int));
for(int i=0; i<n; i++) scanf("%d", &a[i]);
heap_sort(a, n);
for(int i=0; i<n-1; i++){
int check=binary_search(a, i+1, n-1, Q-a[i]);
if(check==1) count++;
}
printf("%d", count);
free(a);
return 0;
}
Problem: Chapter 6 - Word Frequency in Text
Description
Given a TEXT which consists of a sequence of words. Each word is defined to be a sequence of
contiguous characters of the alphabet (a, ..., z, A, ..., Z) and digits (0, 1, ..., 9). Other special characters
are considered as delimiters between words.
Write a program to count the number of occurrences o(w) of each word w of the given TEXT.
Input
The TEXT (each word of the TEXT has length <= 20)
Output
Each line contains a word w and o(w) (separated by a SPACE). The words (printed to lines of the
stdout) are sorted in a lexicographic order.
Example
Input
Output
abc 3
abcd 1
def 2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD_LENGTH 21
#define TABLE_SIZE 200003
Node *hashTable[TABLE_SIZE];
int main() {
char text[1000000];
char word[MAX_WORD_LENGTH];
int idx = 0;
int wordIdx = 0;
return 0;
}
Problem: Chapter 6 - Analyze sales order of an e-commerce company
Description
Data about sales in an e-commerce company (the e-commerce company has several shops) consists
a sequence of lines, each line (represents an order) has the following information:
in which the customer <CustomerID> buys a product <ProductID> with price <Price> at the shop
<ShopID> at the time-point <TimePoint>
Input
The first block is the operational data, which is a sequence of lines (number of lines can be upto
100000), each line contains the information of a submission with above format
The second block is the query block, which is a sequence of lines (number of lines can be upto
100000), each line is a query described above
Output
Example
Input
?total_number_orders
?total_revenue
?revenue_of_shop SHOP001
Output
450
170
40
370
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int a[86400]={0};
char customer_id[23];
char product_id[11];
int i=0, money=0;
int cost;
char shop_id[11];
char time[9];
node *root=NULL, *root1=NULL;
while(1){
scanf("%[^ \n]%*c", customer_id);
if(!strcmp(customer_id, "#")) break;
scanf("%[^ ]%*c", product_id);
scanf("%d%*c", &cost);
scanf("%[^ ]%*c", shop_id);
scanf("%[^\n]%*c", time);
money+=cost;
i++;
}
for(int k=1; k<86400; k++) a[k]+=a[k-1];
char query[30];
while(1){
scanf("%[^ \n]%*c", query);
if(!strcmp(query, "#")) break;
if(!strcmp(query, "?total_number_orders")) printf("%d\n", i);
else if(!strcmp(query, "?total_revenue")) printf("%d\n", money);
else if(!strcmp(query, "?revenue_of_shop")){
char s[11];
scanf("%[^\n]%*c", s);
node *u=find(root, s);
if(u==NULL) printf("0\n");
else printf("%d\n", u->cash);
}
else if(!strcmp(query, "?total_consume_of_customer_shop")){
char s[23];
scanf("%[^\n]%*c", s);
node *u=find(root1, s);
if(u==NULL) printf("0\n");
else printf("%d\n", u->cash);
}
else{
char t1[9], t2[9];
scanf("%[^ ]%*c", t1);
scanf("%[^\n]%*c", t2);
int x=key(t1), y=key(t2);
printf("%d\n", a[y]-a[x-1]);
}
}
return 0;
}
Problem: Chapter 6 - Check Existence in a Set
Description
Cho dãy số nguyên A1, A2, . . . , An với mỗi số nguyên Ai kiểm tra xem có số Aj nào bằng Ai hay
không với j<i.
Input
Output
Ghi ra n dòng, dòng thứ i in ra 1 nếu tồn tại Aj=Ai với j<i, ngược lại in ra 0.
Example
input
14314
output
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int n;
scanf("%d", &n);
node *root=NULL;
int *a=(int *)malloc(n*sizeof(int));
for(int i=0; i<n; i++){
scanf("%d", &a[i]);
if(find(root, a[i])==NULL){
root=insert(root, a[i]);
printf("0\n");
}
else printf("1\n");
}
free(a);
return 0;
}
Problem: Chapter 6 - BST with insertion and removal operations
Description
Each node of a Binary Search Tree (BST) T has a key (keys of nodes must be all different).
Perform a sequence of operations on a Binary Search Tree T (starting from empty BST) including:
insert k: insert a new node having key = k into T (do nothing if the node having key = k
exists)
remove k: remove the node having key = k from T (in case the root is removed, then
replace the root by the smallest-key node of the right sub-tree)
preorder: print (in a new line) the sequence of keys of nodes of T visited by a Pre-Order
traversal (elements are separated by a SPACE character)
postorder: print (in a new line) the sequence of keys of nodes of T visited by a Post-Order
traversal (elements are separated by a SPACE character)
Input
Each line contains a command of three above format
The input is terminated by a line containing #
Output
Example
Input
insert 3
insert 4
remove 4
preorder
postorder
insert 5
insert 1
insert 8
remove 1
preorder
postorder
Output
358
8 5 3k
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
node *root=NULL;
char s[20];
while(1){
scanf("%s", s);
if(!strcmp(s, "#")) break;
if(!strcmp(s, "insert")){
int x; scanf("%d", &x);
root=insert(root, x);
}
else if(!strcmp(s, "preorder")){
preorder(root);
printf("\n");
}
else if(!strcmp(s, "postorder")){
postorder(root);
printf("\n");
}
else{
int x; scanf("%d", &x);
root=removenode(root, x);
}
}
return 0;
}
Problem: Chapter 6 - BST: Build the BST from pre-order sequence of nodes
Description
Given a binary search tree T in which the keys of nodes are distinct positive integers. The sequence of
keys visited when traversing T in a pre-order principle is a1, a2, ..., an. Compute the sequence of keys
visited when traversing T in a post-order principal.
Input
Output
Write the sequence of keys visited when traversing T in a post-order principal (elements
are separated by a SPACE character) if the binary search tree exists, and write NULL,
otherwise.
Example
Input
11
10 5 2 3 8 7 9 20 15 18 40
Output
3 2 7 9 8 5 18 15 40 20 10
Example
Input
11
10 5 2 3 8 7 9 20 15 18 4
Output
NULL
#include <stdio.h>
#include <stdlib.h>
int check;
typedef struct tree{
int key;
struct tree *left_tree;
struct tree *right_tree;
}node;
int main()
{
int n;
scanf("%d", &n);
check=1;
int *a=(int *)malloc(n*sizeof(int));
for(int i=0; i<n; i++) scanf("%d", &a[i]);
node *root=build_tree(a, 0, n-1);
if(check==0) printf("NULL");
else postorder(root);
free(a);
return 0;
}