Code Dsa

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 158

CHAPTER 1:

Chapter 1 - Count words


Description
Given a Text, write a prorgam to count the number Q of words (ignore characters SPACE, TAB,
LineBreak) of this Text

Input

 The Text

Output

 Write the number Q of words

Example

Input

Hanoi University Of Science and Technology

School of Information and Communication Technology

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);
}

Chapter 1 - Convert a TEXT to Upper-Case


Description
Given a TEXT, write a program that converts the TEXT to upper-case.

Input

The TEXT

Output

The TEXT in which characters are converted into upper-case

Example

Input

Hello John,

How are you?

Bye,

Output

HELLO JOHN,

HOW ARE YOU?

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;
}

Chapter 1 - Find all divisor of an integer


Description
Given a positive integer n, find the sequence of (in creasing order) integers q such that n divides q.

Input

 Line 1 contains a positive integer n (1 <= n <= 1000000)

Output

 The sequence of integers q described above

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

 Line 1: contains n (1 <= n <= 1000000)


 Line 2: contains a1, a2, ..., an (-10000 <= ai <= 10000)

Output

 Write the value of Q

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 1: chứa số nguyên dương n (1 <= n <= 1000)

· 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

- input: “papa”, ‘p’, ‘m’

- 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;
}

Chapter 1 - Add two integers


Description
Compute the sum of two integers a and b.

Input

 Line 1 contains two integers a and b (0 <= a, b <= 10 19)

Ouput

Write the sum of a and b

Example

Input

35

Output

8
//C
#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 100

// Function to add two strings representing large numbers


char* addLargeNumbers(char num1[], char num2[]) {
static char result[MAX_LENGTH]; // Static buffer to store the result
int carry = 0;
int len1 = strlen(num1);
int len2 = strlen(num2);
int maxLength = (len1 > len2) ? len1 : len2;
int i, j, k;

// Traverse both strings starting from the least significant digit


for (i = len1 - 1, j = len2 - 1, k = maxLength - 1; k >= 0; i--, j--, k--) {
int digit1 = (i >= 0) ? (num1[i] - '0') : 0; // Convert char to integer
int digit2 = (j >= 0) ? (num2[j] - '0') : 0; // Convert char to integer
int sum = digit1 + digit2 + carry;

result[k] = (sum % 10) + '0'; // Convert integer to char


carry = sum / 10;
}

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];

// Taking input of two large numbers as strings


scanf("%s %s", num1, num2);

// Computing the sum of two large numbers


char* sum = addLargeNumbers(num1, num2);

// Printing the sum


printf("%s\n", sum);
return 0;
}
Chapter 1 - Array Equality
Description
Given two sequence a=a1,…,an and b=b1,…,bm. Check if these sequences are equal.

Input

 Line 1: contains a positive integer T (1≤T≤102) represents number of tests


 Follow are T tests, each of which has the following format

o Line 1: n and m (1≤n,m≤1000)

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);

for (int t = 0; t < T; t++) {


int m, n;
scanf("%d %d", &m, &n);

int a[10000], b[10000];


for (int i = 0; i < m; i++) {
scanf("%d", &a[i]);
}

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


scanf("%d", &b[i]);
}

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

· Dòng 3: văn bản T

Kết quả:

· Ghi văn bản T sau khi thay thế

Ví dụ

Dữ liệu

AI

Artificial Intelligence

Recently, AI is a key technology. AI enable efficient operations in many fields.

Kết quả

Recently, Artificial Intelligence is a key technology. Artificial Intelligence enable efficient operations in
many fields.
#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 1001

void replaceString(char *str, const char *old, const char *new) {


char *pos, temp[MAX_LENGTH];
int index = 0;
int old_len = strlen(old);
int new_len = strlen(new);

while ((pos = strstr(str, old)) != NULL) {


strcpy(temp, str);
index = pos - str;
str[index] = '\0';
strcat(str, new);
strcat(str, temp + index + old_len);
}
}

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);

// Loại bỏ ký tự newline ở cuối các chuỗi


P1[strcspn(P1, "\n")] = '\0';
P2[strcspn(P2, "\n")] = '\0';
T[strcspn(T, "\n")] = '\0';

// Thực hiện thay thế


replaceString(T, P1, P2);

// 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

 Line 1: contains a positive integer n (1 <= n <= 100000)


 Line 2: contains n integers a1, a2, ..., an (elements are separated by a SPACE character)

Output

Write the sum of elements of the given sequence.

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

 Line 1 contains two positive integers n and k (1 <= n, k <= 100)


 Line i+1 (i = 1,2, ..., n): contains the ith row of A (elements are separated by a SPACE
character)
 Line n+2: contains two positive integers k and m (1 <= k,m <= 100)
 Line i+n+2 (i= 1, 2, ..., k): contains the ith row of B (elements are separated by a SPACE
character)

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;

// Reading the dimensions of the first matrix A


scanf("%d %d", &n, &k1);

// Initializing and reading matrix A


int A[n][k1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < k1; j++) {
scanf("%d", &A[i][j]);
}
}

// Reading the dimensions of the second matrix B


scanf("%d %d", &k2, &m);

// Check if the dimensions match for matrix multiplication


if (k1 != k2) {
printf("Matrix multiplication not possible with given dimensions.\n");
return -1;
}

// Initializing and reading matrix B


int B[k2][m];
for (int i = 0; i < k2; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &B[i][j]);
}
}

// Initializing matrix C to store the result


int C[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
C[i][j] = 0;
for (int k = 0; k < k1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}

// Printing the resulting matrix C


for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%d", C[i][j]);
if (j < m - 1) {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Problem: Chapter 1 - Black Column

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

 Write the value of Q

Example

Input

44

1010

1110

1011

1111

Ouput

#include <stdio.h>

int main() {
int n, m;

// Read the number of rows and columns


scanf("%d %d", &n, &m);
int matrix[n][m];

// Read the matrix


for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &matrix[i][j]);
}
}

int blackColumnsCount = 0;

// Check each column


for (int j = 0; j < m; j++) {
int isBlackColumn = 1;
for (int i = 0; i < n; i++) {
if (matrix[i][j] == 0) {
isBlackColumn = 0;
break;
}
}
if (isBlackColumn) {
blackColumnsCount++;
}
}

// Output the number of black columns


printf("%d\n", blackColumnsCount);

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>

// Function to check if a number is even


int is_even(int num) {
return num % 2 == 0;
}

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 prefix_sum[n + 1];


prefix_sum[0] = 0;

// Calculate prefix sum


for (int i = 1; i <= n; i++) {
prefix_sum[i] = prefix_sum[i - 1] + arr[i - 1];
}

int even_count = 0;

// Iterate through the array and count even-weight k-subsequences


for (int i = k; i <= n; i++) {
if (is_even(prefix_sum[i] - prefix_sum[i - k])) {
even_count++;
}
}

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>

Kết thúc dữ liệu là 1 dòng chứa dấu *

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

2022-01-02 10:30:24 dungpq question1

2022-01-03 11:30:24 dungpq question1

2022-02-01 03:30:20 viettq question2

2022-02-01 03:35:20 viettq question1

2022-03-01 03:30:20 viettq question7

2022-01-02 11:20:24 viettq question2

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;

void merge(im arr[], int l, int m, int r)


{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

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

 Line 1 contains 3 integers a, b, c

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;

scanf("%d %d %d", &a, &b, &c);

delta = b*b - 4*a*c;

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

 Line 1 contains 3 integers a, b, c (-10000000 <= a, b, c <= 10000000)

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;

int f(int x){


return x*x*x+a*x*x+ b*x+c;
}
int main()
{
int i=0;
int e[3];
scanf("%d%d%d", &a, &b, &c);
for(int x=1; x<=abs(c)/2; x++){
if(c%x==0){
if(f(x)==0){
e[i]=x; i++;
}
else if(f(-x)==0){
e[i]=-x; i++;
}
}
if(i>3) break;
}
for(int j=0; j<i-1; j++){
for(int h=j+1; h<i; h++){
if(e[j]>e[h]){
int t=e[j]; e[j]=e[h]; e[h]=t;
}
}
}
switch(i){
case 0: printf("NO SOLUTION"); break;
case 1: printf("%d 3", e[0]); break;
case 2:
if(e[0]*e[0]*e[1]==-c) printf("%d 2\n%d 1", e[0], e[1]);
else printf("%d 1\n%d 2", e[0], e[1]);
break;
case 3: printf("%d 1\n%d 1\n%d 1", e[0], e[1], e[2]); break;
}

return 0;
}
Problem: Chapter 1 - Check Sudoku

Description
A matrix 9 x 9 is called a sudoku solution if it satisfies following constraints

 Each element is an integer from 1 to 9


 Elements on each row are distinct
 Elements on each column are distinct
 Elements on each sub-square 3x3 are distinct (the matrix is divided into 9 distinct
subsquares of size 3x3)
Write a program that checks whether or not a given matrix is a sudoku solution

Input

 Line 1: contains a positive integer T which is the number of matrix 9x9


 Subsequent lines are blocks, each block contains a matrix 9x9 with the following format

o Line i (i = 1, 2, ..., 9) contains the ith line of the matrix

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>

// Function to check if a row is valid (contains distinct integers from 1 to 9)


bool isValidRow(int row, int matrix[9][9]) {
bool visited[10] = {false}; // Array to keep track of visited numbers (1 to 9)

for (int j = 0; j < 9; j++) {


int num = matrix[row][j];
if (num < 1 || num > 9 || visited[num]) {
return false; // If the number is out of range or already visited, return false
}
visited[num] = true; // Mark the number as visited
}

return true; // Row is valid


}

// Function to check if a column is valid (contains distinct integers from 1 to 9)


bool isValidColumn(int col, int matrix[9][9]) {
bool visited[10] = {false}; // Array to keep track of visited numbers (1 to 9)

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


int num = matrix[i][col];
if (num < 1 || num > 9 || visited[num]) {
return false; // If the number is out of range or already visited, return false
}
visited[num] = true; // Mark the number as visited
}

return true; // Column is valid


}

// Function to check if a sub-square is valid (contains distinct integers from 1 to 9)


bool isValidSubSquare(int startRow, int startCol, int matrix[9][9]) {
bool visited[10] = {false}; // Array to keep track of visited numbers (1 to 9)

for (int i = startRow; i < startRow + 3; i++) {


for (int j = startCol; j < startCol + 3; j++) {
int num = matrix[i][j];
if (num < 1 || num > 9 || visited[num]) {
return false; // If the number is out of range or already visited, return false
}
visited[num] = true; // Mark the number as visited
}
}

return true; // Sub-square is valid


}

// Function to check if the given matrix is a Sudoku solution


bool isSudokuSolution(int matrix[9][9]) {
// Check each row
for (int i = 0; i < 9; i++) {
if (!isValidRow(i, matrix)) {
return false; // If any row is not valid, return false
}
}

// Check each column


for (int j = 0; j < 9; j++) {
if (!isValidColumn(j, matrix)) {
return false; // If any column is not valid, return false
}
}

// Check each sub-square


for (int i = 0; i < 9; i += 3) {
for (int j = 0; j < 9; j += 3) {
if (!isValidSubSquare(i, j, matrix)) {
return false; // If any sub-square is not valid, return false
}
}
}

return true; // All constraints satisfied, so it is a Sudoku solution


}

int main() {
int T;
scanf("%d", &T);

for (int t = 0; t < T; t++) {


int matrix[9][9];
// Read the matrix
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Check if the matrix is a Sudoku solution and print the result
printf("%d\n", isSudokuSolution(matrix));
}

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:

 find-max: return the maximum element of the given sequence


 find-min: return the minimum element of the given sequence
 sum: return the sum of the elements of the given sequence
 find-max-segment i j: return the maximum element of the subsequence from index i to
index j (i <= j)

Input

 The first block contains the information about the given sequence with the following
format:

o Line 1: contains a positive integer n (1 <= n <= 10000)

o Line 2: contains n integers a1, a2, ..., an (-1000 <= ai <= 1000)

o The first block is terminated by a character *

 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

 Write the result of each query in a corresponding line

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>

#define MAX_N 10000


#define MIN_INT -1001
#define MAX_INT 1001

int main() {
int n, i, j;
int arr[MAX_N];
char query[50];

// Read number of elements


scanf("%d", &n);

// Read the elements of the sequence


for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Skip the termination character '*'


scanf("%s", query);

// 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

 Line 1: contains a positive integer n (1 <= n <= 100000)


 Linw 2: contains n positive integer a1, a2, . . ., an (1 <= ai <= 1000000)

Output

Write the value Q

Example

Input

32479

Output

//C
#include <stdio.h>
#include <math.h>

int checksquare (int n)


{
int x = sqrt(n);
if(x*x ==n) return 1;
else return 0;
}
int main()
{
int N;
scanf("%d", &N);
int dem =0;
int number;
for (int i =0; i<N; i++)
{
scanf("%d", &number);
if(checksquare(number)) dem++;
}
printf("%d", dem);

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

 The float number A

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

 Line 1: contains a positive integer n (1 <= n <= 1000)


 Line i+1 (i = 1,...,n): contains the ith row of the given matrix

Output

 Write the value Q

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:

o Line 1: contains a positive integer N (1 <= N <= 100)

o Line i+1 (i = 1, 2, . . ., N): contains the ith row of the matrix A

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>

// Function to check if two queens attack each other


int areQueensAttacking(int **board, int N) {
// Check rows and columns
for (int i = 0; i < N; i++) {
int rowSum = 0;
int colSum = 0;
for (int j = 0; j < N; j++) {
rowSum += board[i][j];
colSum += board[j][i];
}
if (rowSum > 1 || colSum > 1) {
return 1;
}
}

// 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);

for (int t = 0; t < T; t++) {


int N;
scanf("%d", &N);

// Allocate memory for the board


int **board = (int **)malloc(N * sizeof(int *));
for (int i = 0; i < N; i++) {
board[i] = (int *)malloc(N * sizeof(int));
for (int j = 0; j < N; j++) {
scanf("%d", &board[i][j]);
}
}
// Check if there are two queens attacking each other
int result = areQueensAttacking(board, N);

// Print the result


printf("%d\n", !result);

// 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

 Write in each line X1, X2, ..., Xn separated by a SPACE character

Example

Input

35

Output

113

122

131

212

221

311

#include <stdio.h>

int N;
int sum;
int X[21];
int tong;

int check(int i, int k)


{
if(i<N)
{
return 1;
}
else if (tong + k== sum)
{
return 1;
}
else
{
return 0;
}
}
void printout()
{
for(int i=1; i<=N;i++)
{
printf("%d ", X[i]);
}
printf("\n");
}
void Try (int i)
{
for (int k=1; k<= sum - tong - N+i;k++)
{
if (check(i,k))
{
X[i] =k;
tong += k;
if (i==N)
{
printout();
}
else
{
Try(i+1);
}
tong -= k;
}
}
}
int main(void)
{
scanf("%d %d", &N, &sum);
Try(1);
return 0;
}
Problem: Chapter 2- Subset sum of elements equal to B

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

Write the value Q

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]);
}

// Initialize the dp array


int dp[n + 1][b + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= b; j++) {
if (j == 0) {
dp[i][j] = 1; // Base case: selecting 0 elements sums up to 0
} else {
dp[i][j] = 0;
}
}
}

// Fill the dp array


for (int i = 1; i <= n; i++) {
for (int j = 1; j <= b; j++) {
// Exclude the current element
dp[i][j] = dp[i - 1][j];
// Include the current element if it doesn't exceed the sum
if (a[i - 1] <= j) {
dp[i][j] += dp[i - 1][j - a[i - 1]];
}
}
}

// The answer is in dp[n][b]


printf("%d\n", dp[n][b]);

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)

Fill numbers from 1, 2, 3, .., 9 to 9 x 9 table so that:

 Numbers of each row are distinct


 Numbers of each column are distinct
 Numbers on each sub-square 3 x 3 are distinct

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

 Write the number of solutions found

Example

Input

003400089

006789023

080023456

004065097

060090014

007204365

030602078
000000000

000000000

Output

64

#include <stdio.h>
#include <stdbool.h>

#define N 9

// Function to check if a number can be placed in the given cell


bool isValid(int grid[N][N], int row, int col, int num) {
// Check if the number exists in the current row or column
for (int i = 0; i < N; i++) {
if (grid[row][i] == num || grid[i][col] == num) {
return false;
}
}

// Check if the number exists in the current 3x3 sub-grid


int startRow = row - row % 3;
int startCol = col - col % 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (grid[i + startRow][j + startCol] == num) {
return false;
}
}
}

return true;
}

// Function to solve the Sudoku puzzle using backtracking


int solveSudoku(int grid[N][N]) {
// Find the first empty cell in the grid
int row = -1, col = -1;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (grid[i][j] == 0) {
row = i;
col = j;
break;
}
}
if (row != -1) {
break;
}
}

// If no empty cell is found, the puzzle is solved


if (row == -1) {
return 1;
}

// Try placing numbers from 1 to 9 in the empty cell


int count = 0;
for (int num = 1; num <= 9; num++) {
if (isValid(grid, row, col, num)) {
// If the number can be placed, update the cell and continue solving recursively
grid[row][col] = num;
count += solveSudoku(grid);
// Backtrack
grid[row][col] = 0;
}
}

return count;
}

int main() {
int grid[N][N];

// Input the Sudoku grid


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
scanf("%d", &grid[i][j]);
}
}

// Solve the Sudoku puzzle and print the number of solutions


printf("%d\n", solveSudoku(grid));

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

 Line 1 contains N và M (1 <= N <= 15, 1 <= M <= 1000000).


 Line i+1 (forall i = 1,. . ., N) contains the ith row of the matrix c

Output

Write the number of tours whose length is less than or equal to M.

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;

void findTours(int pos, int current_length) {


if (pos == N) {
// Complete the tour by returning to the starting city
current_length += c[perm[N-1]][perm[0]];
if (current_length <= M) {
count++;
}
return;
}

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


if (!visited[i]) {
perm[pos] = i;
visited[i] = 1;

// Calculate the new length of the tour


int new_length = current_length + c[perm[pos-1]][i];
if (new_length <= M) {
findTours(pos + 1, new_length);
}

visited[i] = 0;
}
}
}

int main() {
scanf("%d %d", &N, &M);

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


for (int j = 0; j < N; j++) {
scanf("%d", &c[i][j]);
}
}

// Initialize
for (int i = 0; i < N; i++) {
visited[i] = 0;
}

// Starting point is city 0


perm[0] = 0;
visited[0] = 1;

// Find all valid tours starting from position 1


findTours(1, 0);

// Output the result


printf("%d\n", count);

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

 Line 1: a positive integer n (1 <= n <= 20)


 Linr i+1 (i = 1, . . ., n): contains the ith row of the distance matrix x (elements are
separated by a SPACE character)

Output

Write the total travel distance of the optimal itinerary found.

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

 Line 1: contains a positive integer m which is the number of steps


 Line i+1 (i = 1, 2, ..., m): contains 2 positive integers X and Y: move a disk from pile X to
pile Y

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.

F[n] = F[n-1] = F[n-2], for n >= 2


Compute F[n] for a given positive integer n

Input

Line 1 : contains a positive integer n (2 <= n <= 100000)

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

 Line 1: contains a positive integer N (1 <= N <= 12)


 Line i+1 (i = 1, 2, . . ., N): contains the ith row of the matrix A

Output

 Write the number of solutions

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;

int check(int i, int k){


if(usedco[i]==1) return 0;
for(int j=0; j<dem; j++){
if(abs(used[j].co-i)==abs(used[j].ro-k)) return 0;
}
return 1;

void Try(int k){


if(usedrow[k]==0){
for(int i=0; i<n; i++){
if(check(i,k)){
usedco[i]=1;
usedrow[k]=1;
used[dem].co=i;
used[dem].ro=k;
dem++;
if(k==n-1) count++;
else Try(k+1);
dem--;
usedco[i]=0;
usedrow[k]=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

Line 1 contains 2 integers a, b (1 <= a, b <= 100000)

Output

Write the greatest common divisor of a and b.

Example

Input
16 24

Output

/******************************************************************************

Welcome to GDB Online.


GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby,
C#, OCaml, VB, Perl, Swift, Prolog, Javascript, Pascal, COBOL, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
#include <stdio.h>

int ucln (int a, int b)


{
if(b==0)
{
return a;
}
else
{
return ucln(b, a%b);
}
}
int main()
{
int a1,b1;
scanf("%d %d", &a1, &b1);
printf("%d", ucln(a1,b1));

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

 Write the binary string representing N

Example

Input

20

Output

10100

#include <stdio.h>

void convertBi (int N)


{
if (N==0) return;
else
{
convertBi (N/2);
printf("%d", N%2);
}
}
int main()
{
int N;
scanf("%d", &N);
convertBi (N);

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

 Line 1: two positive integers k and n (1 <= k,n <= 999)

Output

Write te value C(k,n) modulo 109+7.

Example

Input

35

Output

10

#include <stdio.h>
#define P 1000000007

int combi [1000][1000];


int comb (int k, int n)
{
if (k==0)
{
return 1;
}
else if (k==n)
{
return 1;
}
else
{
if (combi[k][n] ==0 && k!=0)
{
combi[k][n] = (comb(k,n-1) + comb (k-1,n-1)) % P;
}
return combi[k][n];
}
}
int main()
{
int K;
int N;
scanf("%d %d", &K, &N);
printf("%d", comb(K,N));
return 0;
}
Problem: Chapter 2 - Binary sequences generation without consecutive 11

Description
Given an integer n, write a program that generates all binary sequences without consecutive 11 in a
lexicographic order.

Input

 Line 1: contains an integer n (1 <= n <= 20)

Output

Write binary sequences in a lexicographic order, each sequence in a line

Example

Input

Output

000

001

010

100

101

#include <stdio.h>
#define P 1000000007

int X[21];
int N;

int check (int i, int k)


{
if (i==1)
{
return 1;
}
else if (k==1 && X[i-1] == 1)
{
return 0;
}
else
{
return 1;
}
}
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++)
{
if (check(i,k)==1)
{
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 2 - Binary sequence generation

Description
Given an integer n, write a program that generates all the binary sequences of length n in a
lexicographic order.

Input

 Line 1: contains an integer n (1 <= n <= 20)

Output

Write binary sequences in a lexicographic ordder, eac sequence in a line

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

 Dòng 1: ghi 4 số nguyên dương n, m, r, c trong đó n và m tương ứng là số hàng và cột


của ma trận A (1 <= n,m <= 999) và r, c tương ứng là chỉ số hàng, cột của ô xuất phát.
 Dòng i+1 (i=1,...,n): ghi dòng thứ i của ma trận A

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>

typedef struct node{


int a;
struct node *n;
}list;

list *f[2]={NULL}, *l[2];


int n, m;
int ans;
int count[999][999];
int v[999][999]={0};
int b[999][999];

void push(int k, int i){


if(f[i]==NULL){
list *t=(list *)malloc(sizeof(list));
t->a=k;
t->n=NULL;
f[i]=l[i]=t;
}
else{
list *t=(list *)malloc(sizeof(list));
t->a=k;
t->n=NULL;
l[i]->n=t;
l[i]=t;
}
}

void pop(int i){


if(f[i]!=NULL){
list *r=f[i];
f[i]=f[i]->n;
free(r);
}
}

int front(int i){


return f[i]->a;
}

int empty(int i){


if(f[i]!=NULL) return 0;
return 1;
}

int goal(int x, int y){


return x==0 || y==0 || x==n-1 || y==m-1;
}

int up(int x, int y){


if(v[x-1][y]) return 0;
if(goal(x-1, y)){
ans=count[x][y]+1;
return 1;
}
push(x-1, 0); push(y, 1);
v[x-1][y]=1;
count[x-1][y]=count[x][y]+1;
return 0;
}
int right(int x, int y){
if(v[x][y+1]) return 0;
if(goal(x, y+1)){
ans=count[x][y]+1;
return 1;
}
push(x, 0); push(y+1, 1);
v[x][y+1]=1;
count[x][y+1]=count[x][y]+1;
return 0;
}

int down(int x, int y){


if(v[x+1][y]) return 0;
if(goal(x+1, y)){
ans=count[x][y]+1;
return 1;
}
push(x+1, 0); push(y, 1);
v[x+1][y]=1;
count[x+1][y]=count[x][y]+1;
return 0;
}

int left(int x, int y){


if(v[x][y-1]) return 0;
if(goal(x, y-1)){
ans=count[x][y]+1;
return 1;
}
push(x, 0); push(y-1, 1);
v[x][y-1]=1;
count[x][y-1]=count[x][y]+1;
return 0;
}

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);

if(up(x, y)) break;


if(right(x, y)) break;
if(down(x, y)) break;
if(left(x, y)) break;
}
printf("%d", ans);
return 0;
}
Problem: Chapter 3 - Polynomial Manipulation

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

Each polynomial has an identifier which is a positive integer from 1 to 10000

Given a list of commands over polynomials below:

 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

Each line contains a command described above (terminated by a line containing *)

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

typedef struct node{


int coef;
int exp;
struct node *n;
}list;

list *p[N]={NULL}; //p[i] is a pointer to the first element of linked list representing the polynomial id=i

list *makenode(int c, int e){


list *p=(list *)malloc(sizeof(list));
p->coef=c;
p->exp=e;
p->n=NULL;
return p;
}

void addterm(int i, int c, int e){


if(p[i]==NULL){
p[i]=makenode(c, e);
return;
}
for(list *a=p[i]; a!=NULL; a=a->n){
if(a->exp==e){
a->coef+=c;
break;
}
if(p[i]->exp<e){
list *t=makenode(c, e);
t->n=p[i];
p[i]=t;
break;
}
if(a->n==NULL){
list *t=makenode(c, e);
t->n=a->n;
a->n=t;
break;
}
if(a->n->exp<e){
list *t=makenode(c, e);
t->n=a->n;
a->n=t;
break;
}
}
}

int evaluate(int i, int x){


if(p[i]==NULL) return 0;
int value=0;
for(list *a=p[i]; a!=NULL; a=a->n) value=value+a->coef*pow(x, a->exp);
return value;
}

void destroy(int i){


list *freelist=p[i];
while(freelist!=NULL){
p[i]=p[i]->n;
free(freelist);
freelist=p[i];
}
}

void addpoly(int i, int j, int k){


if(p[k]!=NULL) destroy(k);
p[k]=makenode(p[i]->coef, p[i]->exp);
list *last=p[k];
for(list *a=p[i]->n; a!=NULL; a=a->n){
list *t=makenode(a->coef, a->exp);
last->n=t;
last=t;
}
for(list *a=p[j]; a!=NULL; a=a->n) addterm(k, a->coef, a->exp);
}

void print(int i){


for(list *a=p[i]; a!=NULL; a=a->n) printf("%d %d ", a->coef, a->exp);
printf("\n");
}

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

 Dòng 1: ghi số nguyên dương n (1 <= n <= 1000)


 Dòng 2: ghi các số nguyên dương a1, a2, …, an.
 Các dòng tiếp theo lần lượt là các lệnh để thao tác (kết thúc bởi ký hiệu #) với các loại
sau:

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 remove k: loại bỏ phần tử có key bằng k khỏi danh sách

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;

int check [1001] = {0};

Node* makeNode(int n){


Node* tmp = (Node*) malloc(sizeof(Node));
tmp -> data = n;
tmp -> link = NULL;
return tmp;
}
void Display()
{
while (head != NULL)
{
printf("%d ", head -> data);
head = head -> link;
}
}
void freeList(){
Node* to_free=head;
while (to_free != NULL){
head = head->link;
free(to_free);
to_free = head;
}
}

void Addlast(int n){


Node* new = makeNode(n);
if(head == NULL)
{
head = new;
cur = head;
prev = NULL;
}
else
{
Node* temp = head;
while (temp -> link != NULL)
{
temp = temp -> link;
}
temp -> link = new;
}
}

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

Write 1 if the sequence is correct, and write 0, otherwise

Example:

input

(()[][]{}){}{}[][]({[]()})

output

#include <iostream>
#include <stack>
#include <string>

using namespace std;

bool isMatchingPair(char char1, char char2) {


if (char1 == '(' && char2 == ')') return true;
if (char1 == '{' && char2 == '}') return true;
if (char1 == '[' && char2 == ']') return true;
return false;
}

bool isCorrectExpression(const string& expr) {


stack<char> s;
for (char ch : expr) {
if (ch == '(' || ch == '{' || ch == '[') {
s.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']') {
if (s.empty() || !isMatchingPair(s.top(), ch)) {
return false;
}
s.pop();
}
}
return s.empty();
}

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:

 PUSH v: push a value v into the stack


 POP: remove an element out of the stack and print this element to stdout (print NULL if
the stack is empty)

Input

Each line contains a command (operration) of type

 PUSH v
 POP

Output

 Write the results of POP operations (each result is written in a line)

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>

typedef struct Node{


int data;
struct Node *link;
}node;

node* head = NULL;


void push(int x)
{
node* cur = NULL;
cur = (node*)malloc(sizeof(node));
cur -> data = x;
cur -> link = head;
head = cur;
}
int pop()
{
node* p = NULL;
p = (node*)malloc(sizeof(node));
int x= head -> data;
p = head;
head = head -> link;
free(p);
return x;
}
int main()
{

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:

 PUSH v: push a value v into the queue


 POP: remove an element out of the queue and print this element to stdout (print NULL if
the queue is empty)

Input

Each line contains a command (operration) of type

 PUSH v
 POP

Output

 Write the results of POP operations (each result is written in a line)

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>

#define MAX_SIZE 100

// Structure to represent a queue


typedef struct {
int items[MAX_SIZE];
int front;
int rear;
} Queue;

// Function to create a new queue


Queue* createQueue() {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->front = -1;
queue->rear = -1;
return queue;
}

// Function to check if the queue is empty


int isEmpty(Queue* queue) {
return queue->front == -1;
}

// Function to check if the queue is full


int isFull(Queue* queue) {
return (queue->rear + 1) % MAX_SIZE == queue->front;
}

// Function to add an item to the queue


void push(Queue* queue, int value) {
if (isFull(queue)) {
printf("Queue is full\n");
return;
}
if (isEmpty(queue)) {
queue->front = 0;
queue->rear = 0;
} else {
queue->rear = (queue->rear + 1) % MAX_SIZE;
}
queue->items[queue->rear] = value;
}

// Function to remove an item from the queue


int pop(Queue* queue) {
if (isEmpty(queue)) {
printf("NULL\n");
return -1;
}
int removedItem = queue->items[queue->front];
if (queue->front == queue->rear) {
queue->front = -1;
queue->rear = -1;
} else {
queue->front = (queue->front + 1) % MAX_SIZE;
}
printf("%d\n", removedItem);
return removedItem;
}

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

Line 1: contains positive integers a, b, c (1 <= a, b, c <= 900)

Output

write the number of steps or write -1 (if no solution found)

Example

Input

684
Output

#include <stdio.h>
#include <stdlib.h>

typedef struct node{


int a;
struct node *n;
}list;

list *f[2]={NULL}, *l[2];


int a, b, c;
int ans;
int count[900][900];
int v[900][900]={0};

void push(int k, int i){


if(f[i]==NULL){
list *t=(list *)malloc(sizeof(list));
t->a=k;
t->n=NULL;
f[i]=l[i]=t;
}
else{
list *t=(list *)malloc(sizeof(list));
t->a=k;
t->n=NULL;
l[i]->n=t;
l[i]=t;
}
}

void pop(int i){


if(f[i]!=NULL){
list *r=f[i];
f[i]=f[i]->n;
free(r);
}
}

int front(int i){


return f[i]->a;
}

int empty(int i){


if(f[i]!=NULL) return 0;
return 1;
}

int goal(int x, int y){


return x==c || y==c;
}

int filljug1(int x, int y){


if(goal(a, y)){
ans=count[x][y]+1;
return 1;
}
if(v[a][y]) return 0;
push(a, 0); push(y, 1);
v[a][y]=1;
count[a][y]=count[x][y]+1;
return 0;
}

int filljug2(int x, int y){


if(goal(x, b)){
ans=count[x][y]+1;
return 1;
}
if(v[x][b]) return 0;
push(x, 0); push(b, 1);
v[x][b]=1;
count[x][b]=count[x][y]+1;
return 0;
}

void emptyjug1(int x, int y){


if(v[0][y]) return;
push(0, 0); push(y, 1);
v[0][y]=1;
count[0][y]=count[x][y]+1;
}

void emptyjug2(int x, int y){


if(v[x][0]) return;
push(x, 0); push(0, 1);
v[x][0]=1;
count[x][0]=count[x][y]+1;
}
int trans1to2(int x, int y){
int xx, yy;
if(x+y>b){
xx=x+y-b; yy=b;
}
else{
xx=0; yy=x+y;
}
if(goal(xx, yy)){
ans=count[x][y]+1;
return 1;
}
if(v[xx][yy]) return 0;
push(xx, 0); push(yy, 1);
v[xx][yy]=1;
count[xx][yy]=count[x][y]+1;
return 0;
}

int trans2to1(int x, int y){


int xx, yy;
if(x+y>a){
xx=a; yy=x+y-a;
}
else{
xx=x+y; yy=0;
}
if(goal(xx, yy)){
ans=count[x][y]+1;
return 1;
}
if(v[xx][yy]) return 0;
push(xx, 0); push(yy, 1);
v[xx][yy]=1;
count[xx][yy]=count[x][y]+1;
return 0;
}

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);

if(filljug1(x, y)) break;


if(filljug2(x, y)) break;
emptyjug1(x, y);
emptyjug2(x, y);
if(trans1to2(x, y)) break;
if(trans2to1(x, y)) break;
}
printf("%d", ans);
return 0;
}
Problem: Chapter 4 - Tree manipulation and traversal

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:

 MakeRoot u: Tạo ra nút gốc u của 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
 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>

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;
}

Node* find(Node* r, int u) {


if (r == NULL) return NULL;
if (r->id == u) return r;
Node* p = r->leftMostChild;
while (p != NULL) {
Node*q = find(p, u);
if (q != NULL) return q;
p = p->rightSibling;
}
return NULL;
}

void insert(Node* r, int u, int v) {


Node* p = find(r, v);
if (p == NULL) return;
Node *q = makeNode(u);
if (p->leftMostChild == NULL) {
p->leftMostChild = q;
return;
}
Node* h = p->leftMostChild;
while (h->rightSibling != NULL)
h = h->rightSibling;
h->rightSibling = q;
}

void preOrder (Node* r) {


if(r == NULL) return;
printf("%d ", r->id); //visit the root r
Node* p = r->leftMostChild;
while (p != NULL) {
preOrder(p);
p = p->rightSibling;
}
}

void inOrder (Node* r) {


if (r == NULL) return;
Node* p = r->leftMostChild; //the first (left-most) child of r:r1
inOrder(p);
printf("%d ", r->id);
if (p == NULL) return;
p = p->rightSibling; //p = the second child of r:r2
while (p != NULL) {
inOrder(p);
p = p->rightSibling;
}
}

void postOrder (Node* r) {


if (r == NULL) return;
Node* p = r->leftMostChild; //start with the first (left-most) child of r:r1
while (p != NULL) {
postOrder(p);
p = p->rightSibling;
}
printf("%d ", r->id); //lastly, visit the root r
}

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

· MakeRoot u: Tạo ra nút gốc u của 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>

typedef struct node{


int id;
struct node *leftmostchild;
struct node *rightsibling;
struct node *parent;
}node;
node *originalroot=NULL;

node *Makenode(int u){


node *newnode=(node *)malloc(sizeof(node));
newnode->id=u;
newnode->leftmostchild=NULL;
newnode->rightsibling=NULL;
newnode->parent=NULL;
return newnode;
}

// node *find(node *origin,int num){


// if(origin->id==num) return origin;
// if(origin==NULL) return NULL;
// node *new=origin->leftmostchild;
// while(new!= NULL){
// node *temp=find(new, num);
// if(temp != NULL) return temp;
// new=new->rightsibling;
// }
// return NULL;
// }

node * find(node *origin, int u){


if(origin==NULL) return NULL;
else if(origin->id==u) return origin;
else{
node *pl=origin->leftmostchild;
while(pl!= NULL){
node *ne=find(pl, u);
if(ne != NULL) return ne;
pl=pl->rightsibling;
}
}
return NULL;
}

// void insert(int u, int v){


// node *cur=find(originalroot,v);
// if(cur==NULL) return;
// node *tmp=Makenode(u);
// if(cur->leftmostchild==NULL){
// cur->leftmostchild=tmp;
// tmp->parent=cur;
// }
// else{
// node *temp=cur->leftmostchild;
// while(temp->rightsibling != NULL){
// temp=temp->rightsibling;
// }
// temp->rightsibling=tmp;
// tmp->parent=cur;
// }
// return ;
// }

void insert(int u, int v){


node *newnode=Makenode(u);
node *fi=find(originalroot, v);
if(fi==NULL) return;
if(fi->leftmostchild==NULL){
fi->leftmostchild=newnode;
newnode->parent=fi;
}
else{
node *t=fi->leftmostchild;
while(t->rightsibling != NULL){
t=t->rightsibling;
}
t->rightsibling=newnode;
newnode->parent=fi;
}
return ;
}

void preorder(node * origin){


if(origin==NULL) return;
else{
printf("%d ", origin->id);
node *p=origin->leftmostchild;
while(p!=NULL){
preorder(p);
p=p->rightsibling;
}
}
return ;
}

void inorder(node *origin){


if(origin==NULL) return;
else{
node *new=origin->leftmostchild;
inorder(new);
printf("%d ", origin->id);
if(new==NULL) return;
else{
new=new->rightsibling;
while(new!=NULL){
inorder(new);
new=new->rightsibling;

}
}
}
}

void postorder(node *origin){


if(origin==NULL) return;
else{
node *p=origin->leftmostchild;
while(p!=NULL){
postorder(p);
p=p->rightsibling;
}
printf("%d ", origin->id);
}

}
// 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 depth(int u){


// node *newnode=find(originalroot, u);
// int cnt=0;
// while(newnode !=NULL){
// cnt++;
// newnode=newnode->parent;
// }
// return cnt;
// }

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

· MakeRoot u: Tạo ra nút gốc u của 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)

· Height u: Tính và trả về độ cao của nút u

· Depth u: Tính và trả về độ sâu của nút u

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;

node *Makenode(int u){


node *newnode=(node *)malloc(sizeof(node));
newnode->id=u;
newnode->leftmostchild=NULL;
newnode->rightsibling=NULL;
newnode->parent=NULL;
return newnode;
}

node *find(node *origin,int num){


if(origin->id==num) return origin;
if(origin==NULL) return NULL;
node *new=origin->leftmostchild;
while(new!= NULL){
node *temp=find(new, num);
if(temp != NULL) return temp;
new=new->rightsibling;
}
return NULL;
}

void insert(int u, int v){


node *cur=find(originalroot,v);
if(cur==NULL) return;
node *tmp=Makenode(u);
if(cur->leftmostchild==NULL){
cur->leftmostchild=tmp;
tmp->parent=cur;
}
else{
node *temp=cur->leftmostchild;
while(temp->rightsibling != NULL){
temp=temp->rightsibling;
}
temp->rightsibling=tmp;
tmp->parent=cur;
}
return ;
}

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 depth(int u){


node *newnode=find(originalroot, u);
int cnt=0;
while(newnode !=NULL){
cnt++;
newnode=newnode->parent;
}
return cnt;
}

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);

for (int i=0;i<count;i++) printf("%d\n",ans[i]);


}
Problem: Chapter 4 - Family Tree

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:

 descendants <name>: return number of descendants of the given <name>


 generation <name>: return the number of generations of the descendants of the given
<name>

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

Each line is the result of a corresponding query.

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>

#define MAX_PEOPLE 104


#define MAX_NAME_LEN 50

typedef struct Person {


char name[MAX_NAME_LEN];
struct Person* children[MAX_PEOPLE];
int childCount;
} Person;

Person* family[MAX_PEOPLE];
int familyCount = 0;

Person* findOrCreatePerson(char* name) {


for (int i = 0; i < familyCount; i++) {
if (strcmp(family[i]->name, name) == 0) {
return family[i];
}
}
Person* newPerson = (Person*)malloc(sizeof(Person));
strcpy(newPerson->name, name);
newPerson->childCount = 0;
family[familyCount++] = newPerson;
return newPerson;
}

int countDescendants(Person* person) {


if (person->childCount == 0) return 0;
int count = person->childCount;
for (int i = 0; i < person->childCount; i++) {
count += countDescendants(person->children[i]);
}
return count;
}

int findGenerations(Person* person) {


if (person->childCount == 0) return 0;
int maxGen = 0;
for (int i = 0; i < person->childCount; i++) {
int childGen = findGenerations(person->children[i]);
if (childGen > maxGen) {
maxGen = childGen;
}
}
return maxGen + 1;
}

int main() {
char child[MAX_NAME_LEN], parent[MAX_NAME_LEN];

// Read family tree relations


while (scanf("%s", child) == 1 && strcmp(child, "***") != 0) {
scanf("%s", parent);
Person* parentNode = findOrCreatePerson(parent);
Person* childNode = findOrCreatePerson(child);
parentNode->children[parentNode->childCount++] = childNode;
}

char command[MAX_NAME_LEN], name[MAX_NAME_LEN];

// Read and execute queries


while (scanf("%s", command) == 1 && strcmp(command, "***") != 0) {
scanf("%s", name);
Person* person = findOrCreatePerson(name);
if (strcmp(command, "descendants") == 0) {
printf("%d\n", countDescendants(person));
} else if (strcmp(command, "generation") == 0) {
printf("%d\n", findGenerations(person));
}
}

// Free allocated memory


for (int i = 0; i < familyCount; i++) {
free(family[i]);
}

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)

 MakeRoot u: tạo một nút gốc có id bằng u


 AddLeft u v: tạo một nút có id = u và chèn vào vị trí con trái của nút có id bằng v trên T
(không thực hiện hành động chèn nếu nút có id bằng u đã tồn tại hoặc nút có id bằng v
không tồn tại hoặc nút có id bằng v đã có nút con trái rồi)
 AddRight u v: tạo một nút có id = u và chèn vào vị trí con phải của nút có id bằng v trên
T (không thực hiện hành động chèn nếu nút có id bằng u đã tồn tại hoặc nút có id bằng
v không tồn tại hoặc nút có id bằng v đã có nút con phải rồi)
 PreOrder: đưa ra trên 1 dòng mới dãy id của các nút trong phép duyệt cây T theo thứ tự
trước (các phần tử cách nhau bởi đúng 1 ký tự cách SPACE)
 InOrder: đưa ra trên 1 dòng mới dãy id của các nút trong phép duyệt cây T theo thứ tự
giữa (các phần tử cách nhau bởi đúng 1 ký tự cách SPACE)
 PostOrder: đưa ra trên 1 dòng mới dãy id của các nút trong phép duyệt cây T theo thứ tự
sau (các phần tử cách nhau bởi đúng 1 ký tự cách SPACE)
Input

 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;
}

Node* find(int u, Node* r) {


if (r == NULL) {
return NULL;
}
if (r->id == u) {
return r;
}
Node* p = find(u, r->leftChild);
if (p != NULL) {
return p;
}
return find(u, r->rightChild);
}

void addLeft(int u, int v, Node* r) {


Node* p = find(v, r);
if (p == NULL) {
return;
}
if (p->leftChild != NULL) {
return;
}
Node* q = find(u, r);
if (q != NULL) {
return;
}
p->leftChild = makeNode(u);
}

void addRight(int u, int v, Node* r) {


Node* p = find(v, r);
if (p == NULL) {
return;
}
if (p->rightChild != NULL) {
return;
}
Node* q = find(u, r);
if (q != NULL) {
return;
}
p->rightChild = makeNode(u);
}

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

 Line 1 contains MakeRoot u: make the root of the tree having id = u


 Each subsequent line contains: AddLeft or AddRightcommands with the format
 AddLeft u v: create a node having id = u, add this node as a left-child of the node with id
= v (if not exists)
 AddRight u v: create a node having id = u, add this node as a right-child of the node with
id = v (if not exists)
 The last line contains * which marks the end of the 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;
}

void addLeft (int u, int v)


{
if (array[u] != NULL) return;
if (array[v] == NULL) return;
if (array[v] -> leftchild != NULL) return;
array[v] -> leftchild = makeNode(u);
}

void addRight (int u, int v)


{
if (array[u] != NULL) return;
if (array[v] == NULL) return;
if (array[v] -> rightchild != NULL) return;
array[v] -> rightchild = makeNode(u);
}

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

 Line 1: contains an integer n (1 <= n <= 1000000)


 Line 2: a1, a2, ..., an. (0 <= ai <= 100000)

Output

Write the sorted sequence, elements are separated by a SPACE chharacter.

Example

Input

1342

Output

1234

#include <stdio.h>

void swap (int *m, int *n)


{
int t = *m;
*m = *n;
*n = t;
}
void heapify(int arr[], int i, int n)
{
int left = 2*i;
int right = 2*i +1;
int max = i;
if (left<=n && arr[left] > arr[max])
{
max = left;
}
if (right <=n && arr[right] > arr[max])
{
max = right;
}
if (max != i)
{
swap (&arr[i], &arr[max]);
heapify(arr, max, n);
}
}
void buildheap (int arr[], int n)
{
for (int i=n/2; i>=1; i--)
{
heapify(arr, i, n);
}
}
void heapsort(int arr[], int n)
{
buildheap(arr,n);
for (int i =n; i>=2; i--)
{
swap (&arr[1], &arr[i]);
heapify(arr, 1, i-1);
}
}
int main()
{
int n;
scanf("%d", &n);
int arr[n];
for (int i=1; i<=n; i++)
{
scanf("%d", &arr[i]);
}
heapsort(arr, n);
for (int i=1; i<=n; i++)
{
printf("%d ", arr[i]);
}

}
Problem: Chapter 5 - Sort Strings
Description
Given a sequence of strings S1, S2, . . ., Sn. Sort the given sequence in non-decreasing order.

Input

 Line 1: contains a positive integer n (1 <= n <= 100000)


 Line i+1 (i = 1, 2, ..., n): contains Si

Output

 Write in each line a string in the sorted sequence

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

 Line 1: contains a positive integer n (1 <= n <= 100000)


 Line i+1 (i = 1, 2, ..., n): contains a string <studentID> and a positive integer <grade> in
which <grade> is the total grade of student <studentID>

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;

void swap(int i, int j){


profile t=p[i]; p[i]=p[j]; p[j]=t;
}

void heapifygrade(int i, int n){


int L=2*i+1;
int R=L+1;
int max=i;

if(L<n && p[max].g<p[L].g) max=L;


if(R<n && p[max].g<p[R].g) max=R;

if(max!=i){
swap(max, i);
heapifygrade(max, n);
}
}

void heapsortgrade(){
for(int i=n/2-1; i>=0; i--){
heapifygrade(i, n);
}

for(int i=n-1; i>=1; i--){


swap(0, i);
heapifygrade(0, i);
}
}

void heapifyID(int i, int n){


int L=2*i+1;
int R=L+1;
int max=i;

if(L<n && strcmp(p[max].ID, p[L].ID)<0) max=L;


if(R<n && strcmp(p[max].ID, p[R].ID)<0) max=R;

if(max!=i){
swap(max, i);
heapifyID(max, n);
}
}

void heapsortID(){
for(int i=n/2-1; i>=0; i--){
heapifyID(i, n);
}

for(int i=n-1; i>=1; i--){


swap(0, i);
heapifyID(0, i);
}
}

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>

#define MAX_N 100000


#define MAX_M 10

// Structure to hold vector and its index


typedef struct {
int vector[MAX_M];
int index;
} VectorIndex;

// Function to swap two vectors


void swap(VectorIndex *a, VectorIndex *b) {
VectorIndex temp = *a;
*a = *b;
*b = temp;
}

// Comparator function for heap sort


int compare_vectors(const void *a, const void *b) {
VectorIndex *va = (VectorIndex *)a;
VectorIndex *vb = (VectorIndex *)b;

// Compare vectors element by element


for (int i = 0; i < MAX_M; i++) {
if (va->vector[i] != vb->vector[i]) {
return va->vector[i] - vb->vector[i];
}
}

return 0;
}

// Function to heapify a subtree rooted with node i which is an index in arr[]


// n is size of heap
void heapify(VectorIndex arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left = 2*i + 1
int right = 2 * i + 2; // right = 2*i + 2

// If left child is larger than root


if (left < n && compare_vectors(&arr[left], &arr[largest]) > 0)
largest = left;

// If right child is larger than largest so far


if (right < n && compare_vectors(&arr[right], &arr[largest]) > 0)
largest = right;

// If largest is not root


if (largest != i) {
swap(&arr[i], &arr[largest]);

// Recursively heapify the affected sub-tree


heapify(arr, n, largest);
}
}

// Main function to do heap sort


void heap_sort(VectorIndex arr[], int n) {
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

// One by one extract an element from heap


for (int i = n - 1; i >= 0; i--) {
// Move current root to end
swap(&arr[0], &arr[i]);

// call max heapify on the reduced heap


heapify(arr, i, 0);
}
}

int main() {
int n, m;
VectorIndex vectors[MAX_N];

// Read n and m
scanf("%d %d", &n, &m);

// Read vectors A[1], A[2], ..., A[n]


for (int i = 0; i < n; i++) {
vectors[i].index = i; // Store original index
for (int j = 0; j < m; j++) {
scanf("%d", &vectors[i].vector[j]);
}
}

// Sort vectors using heap sort


heap_sort(vectors, n);

// Output sorted vectors


for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%d", vectors[i].vector[j]);
if (j < m - 1) {
printf(" ");
}
}
printf("\n");
}

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

 Line 1 contains 2 positive integers n and m (1 <= n,m <= 100000)


 Line 2: contains n positive integers a1, a2, . . ., an (1 <= ai <= 1000000)
 Line 3: contains m positive integers b1, b2, . . ., bm (1 <= ai <= 1000000)

Output

Write the cardinalnity of the subset found.

Example

Input

66

7 3 10 1 2 8

6 2 8 10 5 7

Output
4

Explanation. The max-cardinality common subset of A and B is {2, 8, 10, 7}

#include <stdio.h>
#include <stdlib.h>

void swap(int a[], int i, int j){


int t=a[i]; a[i]=a[j]; a[j]=t;
}

void heapify(int a[], int i, int n){


int L=2*i+1;
int R=L+1;
int max=i;

if(L<n && a[max]<a[L]) max=L;


if(R<n && a[max]<a[R]) max=R;

if(max!=i){
swap(a, i, max);
heapify(a, max, n);
}
}

void heapsort(int a[], int n){


for(int i=n/2-1; i>=0; i--) heapify(a, i, n);
for(int i=n-1; i>=1; i--){
swap(a, 0, i);
heapify(a, 0, i);
}
}

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);

int u, v, count; count=v=u=0;


while(v<n && u<m){
if(a[v]==b[u]){
u++;
v++;
count++;
}
else if(a[v]<b[u]) v++;
else u++;
}
printf("%d", count);
return 0;
}
Problem: Chapter 5 - Sort candidates of a Contest

Description
A candidate of a contest has following information:

 code: string of length from 2 to 10


 score: integer from 0 to 1000000 (scores of candidates are distinct)

Write a program to sort the list of candidates in non-increasing order of scores.

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>

typedef struct candidate{


char code[11];
int score;
}candidate;

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;
}

void swap(candidate a[], int i, int j){


candidate tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}

void Heapify(candidate a[], int i, int t){


int L=2*i;
int R=2*i+1;
int maxIdx=i;
if(L<=t && cmp(a,L,maxIdx)==1) maxIdx=L;
if(R<=t && cmp(a,R,maxIdx)==1) maxIdx=R;
if(maxIdx !=i){
swap(a, i, maxIdx);
Heapify(a,maxIdx, t);
}
}

void BuildHeap(candidate a[]){


for(int i= n/2; i>=1; i--){
Heapify(a,i,n);
}
}

void HeapSort(candidate a[]){


BuildHeap(a);
for(int i=n; i>=2; i--){
swap(a, 1,i);
Heapify(a, 1, i-1);
}
}

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

•Each line contains command under the form: “insert k”

•The input is terminated by a line containing #

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>

// Define the structure of a BST node


struct Node {
int key;
struct Node* left;
struct Node* right;
};

// Function to create a new BST node


struct Node* newNode(int key) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->key = key;
node->left = node->right = NULL;
return node;
}

// Function to insert a key into the BST


struct Node* insert(struct Node* node, int key) {
// If the tree is empty, return a new node
if (node == NULL) return newNode(key);

// Otherwise, recur down the tree


if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);

// Return the (unchanged) node pointer


return node;
}

// Function to perform pre-order traversal of the BST


void preOrder(struct Node* node) {
if (node != NULL) {
printf("%d ", node->key);
preOrder(node->left);
preOrder(node->right);
}
}

int main() {
struct Node* root = NULL;
char command[20];
int key;

// Read input commands until "#" is encountered


while (1) {
scanf("%s", command);
if (command[0] == '#') break;

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:

<from_account> <to_account> <money> <time_point> <atm>

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)

A transaction cycle of length k starting from account a1 is defined to be a sequence of distinct


account a1, a2, …, ak in which there are transactions from account a1 to a2, from a2 to a3, …, from
ak to a1.

Write a program that process the following queries:

 ?total_money_transaction_from <account>: compute the total amount of money


transferred from the account <account>

Input (stdin)

The input consists of 2 blocks of information: the data block and the query block

• The data block consists of lines:

o Each line contains the information about a transaction described above

o The data is terminated by a line containing #

• The query block consists of lines:


o Each line is a query described above

o The query block is terminated by a line containing #

Output (stdout)

• Print to stdout (in each line) the result of each query described above

Example

Input

T000010010 T000010020 1000 10:20:30 ATM1

T000010010 T000010030 2000 10:02:30 ATM2

T000010010 T000010040 1500 09:23:30 ATM1

T000010020 T000010030 3000 08:20:31 ATM1

T000010030 T000010010 4000 12:40:00 ATM2

T000010040 T000010010 2000 10:30:00 ATM1

T000010020 T000010040 3000 08:20:31 ATM1

T000010040 T000010030 2000 11:30:00 ATM1

T000010040 T000010030 1000 18:30:00 ATM1

?total_money_transaction_from T000010010

?total_money_transaction_from T000010030

Output

4500

4000

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct tree{


char account[21];
struct tree *left;
struct tree *right;
int cash;
}node;
node *makenode(char x[], int c){
node *p=(node *)malloc(sizeof(node));
strcpy(p->account, x);
p->left=NULL;
p->right=NULL;
p->cash=c;
return p;
}

node *find(node *r, char u[]){


if(r==NULL) return NULL;
if(!strcmp(r->account, u)) return r;
else if(strcmp(r->account, u)>0) return find(r->left, u);
return find(r->right, u);
}

node *insert(node *r, char k[], int c){


if(r==NULL){
r=makenode(k, c);
return r;
}
if(strcmp(r->account, k)>0) r->left=insert(r->left, k, c);
else if(strcmp(r->account, k)<0) r->right=insert(r->right, k, c);
return r;
}

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

Each line contains the result (0 or 1) of the corresponding action.

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>

#define TABLE_SIZE 200003

typedef struct Node {


uint64_t key;
struct Node *next;
} Node;

Node *hashTable[TABLE_SIZE];

unsigned int hash(uint64_t key) {


return key % TABLE_SIZE;
}

Node *createNode(uint64_t key) {


Node *newNode = (Node *)malloc(sizeof(Node));
newNode->key = key;
newNode->next = NULL;
return newNode;
}

int find(uint64_t key) {


unsigned int index = hash(key);
Node *current = hashTable[index];
while (current != NULL) {
if (current->key == key) {
return 1;
}
current = current->next;
}
return 0;
}

int insert(uint64_t key) {


unsigned int index = hash(key);
Node *current = hashTable[index];
while (current != NULL) {
if (current->key == key) {
return 0;
}
current = current->next;
}
Node *newNode = createNode(key);
newNode->next = hashTable[index];
hashTable[index] = newNode;
return 1;
}

int main() {
char line[256];
uint64_t key;

// Initialize hash table


for (int i = 0; i < TABLE_SIZE; i++) {
hashTable[i] = NULL;
}

// 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));
}
}

// Free allocated memory


for (int i = 0; i < TABLE_SIZE; i++) {
Node *current = hashTable[i];
while (current != NULL) {
Node *temp = current;
current = current->next;
free(temp);
}
}

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:

 insert k: insert a new node having key = k into T


 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

 Write the information of preorder, postorder commands described above

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>

// Definition of the node structure


typedef struct Node {
int key;
struct Node* left;
struct Node* right;
} Node;

// Function to create a new node


Node* createNode(int key) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to insert a node in the BST


Node* insert(Node* root, int key) {
if (root == NULL) {
return createNode(key);
}
if (key < root->key) {
root->left = insert(root->left, key);
} else if (key > root->key) {
root->right = insert(root->right, key);
}
return root;
}

// Function to perform pre-order traversal


void preorder(Node* root) {
if (root != NULL) {
printf("%d ", root->key);
preorder(root->left);
preorder(root->right);
}
}

// Function to perform post-order traversal


void postorder(Node* root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->key);
}
}

// Function to clear the trailing space and print a new line


void printPreorder(Node* root) {
preorder(root);
printf("\n");
}

void printPostorder(Node* root) {


postorder(root);
printf("\n");
}

// Main function to read input and perform operations


int main() {
Node* root = NULL;
char command[10];
int key;

while (scanf("%s", command) == 1) {


if (command[0] == '#') {
break;
}
if (command[0] == 'i') { // "insert"
scanf("%d", &key);
root = insert(root, key);
} else if (command[0] == 'p') {
if (command[1] == 'r') { // "preorder"
printPreorder(root);
} else if (command[1] == 'o') { // "postorder"
printPostorder(root);
}
}
}

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:

H(s) = (s[1]*256k-1 + s[2]*256k-2 + . . . + s[k]*2560 ) mod m (the contant integer m is a parameter)

Given a sequence of strings k1, k2, …, kn, compute the corresponding hash codes

Input

Line 1: n and m (1 <= n,m <= 100000)

Line i+1 (i = 1,2,…,n): contains the string ki (the length of each string is less than or equal to 200)

Output

Each line contains the corresponding hash code of n given strings

Example

Input

4 1000

ab

abc

abcd

Output

97
930

179

924

#include <stdio.h>
#include <string.h>

#define BASE 256

// Function to compute the hash code of a given string with parameter m


unsigned long long computeHash(char* s, int m) {
unsigned long long hash = 0;
int length = strlen(s);
for (int i = 0; i < length; i++) {
hash = (hash * BASE + s[i]) % m;
}
return hash;
}

int main() {
int n, m;
scanf("%d %d", &n, &m);

char s[201]; // Buffer to read each string (length <= 200)

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


scanf("%s", s);
printf("%llu\n", computeHash(s, 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

Each line contains the result (0 or 1) of the corresponding action.

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

typedef struct Node {


char key[MAX_KEY_LENGTH];
struct Node *next;
} Node;

Node *hashTable[TABLE_SIZE];

unsigned int hash(const char *key) {


unsigned int hash = 0;
while (*key) {
hash = (hash * 31) + *key++;
}
return hash % TABLE_SIZE;
}

Node *createNode(const char *key) {


Node *newNode = (Node *)malloc(sizeof(Node));
strcpy(newNode->key, key);
newNode->next = NULL;
return newNode;
}

int find(const char *key) {


unsigned int index = hash(key);
Node *current = hashTable[index];
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
return 1;
}
current = current->next;
}
return 0;
}

int insert(const char *key) {


unsigned int index = hash(key);
Node *current = hashTable[index];
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
return 0;
}
current = current->next;
}
Node *newNode = createNode(key);
newNode->next = hashTable[index];
hashTable[index] = newNode;
return 1;
}

int main() {
char line[MAX_KEY_LENGTH + 10];
char key[MAX_KEY_LENGTH];
char cmd[10];

// Initialize hash table


for (int i = 0; i < TABLE_SIZE; i++) {
hashTable[i] = NULL;
}

// 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));
}
}

// Free allocated memory


for (int i = 0; i < TABLE_SIZE; i++) {
Node *current = hashTable[i];
while (current != NULL) {
Node *temp = current;
current = current->next;
free(temp);
}
}

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

•Line 1: contains two integers nand Q (1 <= n,Q<= 106)

•Line 2: contains a1, a2, …, an

Ouput

•Write the value of M

Example

Input

58

46532

Output

#include <stdio.h>
#include <stdlib.h>

void swap(int *a, int *b){


int c;
c=*a, *a=*b; *b=c;
}

void heapify(int a[], int i, int n){


int l=2*i+1;
int r=l+1;
int max=i;

if(l<n && a[l]>a[max]) max=l;


if(r<n && a[r]>a[max]) max=r;

if(max!=i){
swap(&a[max], &a[i]);
heapify(a, max, n);
}
}

void heap_sort(int a[], int n){


for(int i=n/2-1; i>=0; i--) heapify(a, i, n);
for(int i=n-1; i>=1; i--){
swap(&a[0], &a[i]);
heapify(a, 0, i);
}
}

int binary_search(int a[], int start, int end, int k){


if(start>end) return 0;
if(start==end){
if(a[end]==k) return 1;
else return 0;
}
int middle=(start+end)/2;
if(a[middle]==k) return 1;
if(a[middle]<k) return binary_search(a, middle+1, end, k);
else return binary_search(a, start, middle-1, k);
}

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

abc def abc

abc abcd def

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

typedef struct Node {


char word[MAX_WORD_LENGTH];
int count;
struct Node *next;
} Node;

Node *hashTable[TABLE_SIZE];

unsigned int hash(const char *word) {


unsigned int hash = 0;
while (*word) {
hash = (hash * 31) + tolower(*word++);
}
return hash % TABLE_SIZE;
}

Node *createNode(const char *word) {


Node *newNode = (Node *)malloc(sizeof(Node));
strcpy(newNode->word, word);
newNode->count = 1;
newNode->next = NULL;
return newNode;
}

void insertOrUpdate(const char *word) {


unsigned int index = hash(word);
Node *current = hashTable[index];
while (current != NULL) {
if (strcmp(current->word, word) == 0) {
current->count++;
return;
}
current = current->next;
}
Node *newNode = createNode(word);
newNode->next = hashTable[index];
hashTable[index] = newNode;
}

void processWord(char *word) {


// Convert to lowercase
for (char *p = word; *p; ++p) *p = tolower(*p);
insertOrUpdate(word);
}

int compareNodes(const void *a, const void *b) {


Node *nodeA = *(Node **)a;
Node *nodeB = *(Node **)b;
return strcmp(nodeA->word, nodeB->word);
}

int main() {
char text[1000000];
char word[MAX_WORD_LENGTH];
int idx = 0;
int wordIdx = 0;

// Initialize hash table


for (int i = 0; i < TABLE_SIZE; i++) {
hashTable[i] = NULL;
}

// Read entire input text


while (fgets(text + idx, sizeof(text) - idx, stdin)) {
idx += strlen(text + idx);
}

// Parse words and update counts


for (int i = 0; i < idx; i++) {
if (isalnum(text[i])) {
if (wordIdx < MAX_WORD_LENGTH - 1) {
word[wordIdx++] = text[i];
}
} else {
if (wordIdx > 0) {
word[wordIdx] = '\0';
processWord(word);
wordIdx = 0;
}
}
}
// Final word processing if the text ends with a word character
if (wordIdx > 0) {
word[wordIdx] = '\0';
processWord(word);
}

// Collect all nodes for sorting


Node *nodes[TABLE_SIZE];
int nodeCount = 0;
for (int i = 0; i < TABLE_SIZE; i++) {
Node *current = hashTable[i];
while (current != NULL) {
nodes[nodeCount++] = current;
current = current->next;
}
}

// Sort nodes lexicographically by word


qsort(nodes, nodeCount, sizeof(Node *), compareNodes);
// Print sorted words and their counts
for (int i = 0; i < nodeCount; i++) {
printf("%s %d\n", nodes[i]->word, nodes[i]->count);
}

// Free allocated memory


for (int i = 0; i < TABLE_SIZE; i++) {
Node *current = hashTable[i];
while (current != NULL) {
Node *temp = current;
current = current->next;
free(temp);
}
}

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:

<CustomerID> <ProductID> <Price> <ShopID> <TimePoint>

in which the customer <CustomerID> buys a product <ProductID> with price <Price> at the shop
<ShopID> at the time-point <TimePoint>

 <CustomerID>: string of length from 3 to 10


 <ProductID>: string of length from 3 to 10
 <Price>: a positive integer from 1 to 1000
 <ShopID>: string of length from 3 to 10
 <TimePoint>: string representing time-point with the format HH:MM:SS (for example,
09:45:20 means the time-point 9 hour 45 minutes 20 seconds)

Perform a sequence of queries of following types:

 ?total_number_orders: return the total number of orders


 ?total_revenue: return the total revenue the e-commerce company gets
 ?revenue_of_shop <ShopID>: return the total revenue the shop <ShopID> gets
 ?total_consume_of_customer_shop <CustomerID> <ShopID>: return the total revenue
the shop <ShopID> sells products to customer <CustomerID>
 ?total_revenue_in_period <from_time> <to_time>: return the total revenue the e-
commerce gets of the period from <from_time> to <to_time> (inclusive)

Input

The input consists of two blocks of data:

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 first block is terminated with a line containing the character #

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

The second block is terminated with a line containing the character #

Output

Write in each line, the result of the corresponding query

Example

Input

C001 P001 10 SHOP001 10:30:10

C001 P002 30 SHOP001 12:30:10

C003 P001 40 SHOP002 10:15:20

C001 P001 80 SHOP002 08:40:10

C002 P001 130 SHOP001 10:30:10

C002 P001 160 SHOP003 11:30:20

?total_number_orders

?total_revenue

?revenue_of_shop SHOP001

?total_consume_of_customer_shop C001 SHOP001


?total_revenue_in_period 10:00:00 18:40:45

Output

450

170

40

370

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct tree{


char shop[23];
int cash;
struct tree *left;
struct tree *right;
}node;

node *makenode(char x[], int c){


node *p=(node *)malloc(sizeof(node));
strcpy(p->shop, x);
p->left=NULL;
p->right=NULL;
p->cash=c;
return p;
}

node *find(node *r, char u[]){


if(r==NULL) return NULL;
if(!strcmp(r->shop, u)) return r;
else if(strcmp(r->shop, u)>0) return find(r->left, u);
return find(r->right, u);
}

node *insert(node *r, char k[], int c){


if(r==NULL){
r=makenode(k, c);
return r;
}
if(strcmp(r->shop, k)>0) r->left=insert(r->left, k, c);
else if(strcmp(r->shop, k)<0) r->right=insert(r->right, k, c);
return r;
}

int key(char s[]){


int a[3], i=0;
char *c=strtok(s, ":");
while(c!=NULL){
a[i++]=atoi(c);
c=strtok(NULL, ":");
}
return a[0]*60*60+a[1]*60+a[2];
}

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);

node *t=find(root, shop_id);


if(t==NULL) root=insert(root, shop_id, cost);
else t->cash+=cost;

strcat(customer_id, " ");


strcat(customer_id, shop_id);
node *v=find(root1, customer_id);
if(v==NULL) root1=insert(root1, customer_id, cost);
else v->cash+=cost;
int index=key(time);
a[index]+=cost;

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

Dòng đầu chứa số n (1≤n≤100,000)


Dòng hai chứa nn số nguyên A1, A2, ..., An (1≤Ai≤1000,000,000)

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>

typedef struct tree{


int a;
struct tree *left;
struct tree *right;
}node;

node *makenode(int x){


node *p=(node *)malloc(sizeof(node));
p->a=x;
p->left=NULL;
p->right=NULL;
return p;
}

node *find(node *r, int u){


if(r==NULL) return NULL;
if(r->a==u) return r;
else if(r->a > u) return find(r->left, u);
return find(r->right, u);
}
node *insert(node *r, int k){
if(r==NULL){
r=makenode(k);
return r;
}
if(r->a > k) r->left=insert(r->left, k);
else if(r->a < k) r->right=insert(r->right, k);
return r;
}

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

Write the information of preorder, postorder commands described above

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>

typedef struct tree{


int key;
struct tree *right;
struct tree *left;
}node;

node *makenode(int x){


node *p=(node *)malloc(sizeof(node));
p->key=x;
p->right=NULL;
p->left=NULL;
return p;
}

node *insert(node *r, int x){


if(r==NULL) r=makenode(x);
else if(r->key > x) r->left=insert(r->left, x);
else if(r->key < x) r->right=insert(r->right, x);
return r;
}

node *removeroot(node *r){


if(r==NULL) return NULL;
if(r->right==NULL){
node *t=r;
r=r->left;
free(t);
return r;
}
node *p=r->right;
if(p->left==NULL){
node *t=p;
r->key=p->key;
r->right=p->right;
free(t);
return r;
}
node *u;
while(p->left!=NULL){
u=p;
p=p->left;
}
u->left=p->right;
r->key=p->key;
free(p);
return r;
}

node *removenode(node *r, int x){


if(r==NULL) return NULL;
if(r->key==x) return removeroot(r);
else if(r->key > x) r->left=removenode(r->left, x);
else r->right=removenode(r->right, x);
return r;
}

void preorder(node *r){


if(r==NULL) return;
printf("%d ", r->key);
preorder(r->left);
preorder(r->right);
}

void postorder(node *r){


if(r==NULL) return;
postorder(r->left);
postorder(r->right);
printf("%d ", r->key);
}

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

 Line 1: contains a positive integer n (1 <= n <= 50000)


 Line 2: contains a sequence of distinct positive integer a1, a2, ..., an (1 <= ai <= 1000000)

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;

node *makenode(int x){


node *p=(node *)malloc(sizeof(node));
p->key=x;
p->left_tree=NULL;
p->right_tree=NULL;
return p;
}

void postorder(node *r){


if(r==NULL) return;
postorder(r->left_tree);
postorder(r->right_tree);
printf("%d ", r->key);
}

node *build_tree(int a[], int start, int end){


if(start>end) return NULL;
if(start==end) return makenode(a[start]);
node *r=makenode(a[start]);
int i=start+1;
while(i<=end && a[i]<a[start]) i++;
for(int j=i; j<=end; j++){
if(a[j]<a[start]){
check=0;
break;
}
}
r->left_tree=build_tree(a, start+1, i-1);
r->right_tree=build_tree(a, i, end);
return r;
}

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;
}

You might also like