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

/*
insert x: 連結リストの先頭にキー x を持つ要素を継ぎ足す
delete x: キー x を持つ最初の要素を連結リストから削除する
deleteFirst: リストの先頭の要素を削除する
deleteLast: リストの末尾の要素を削除する
*/

struct doubleList{

	struct doubleList *prev;
	int value;
	struct doubleList *next;

};
typedef struct doubleList DL;

void insert(int key);	//連結リストの先頭にキー x を持つ要素を継ぎ足す
void delete(int key);	//キー x を持つ最初の要素を連結リストから削除する
void deleteFirst(void);	//リストの先頭の要素を削除する
void deleteLast(void);	//リストの末尾の要素を削除する

void initialize(DL *p);
void displayAll(DL *p);

DL* gotoHead(DL *p);

DL *listHead;

int size;

int main(void)
{

	int n;
	int i;
	int key;

	size = 0;

	char order[100];
	char str[100];

	//まずリストヘッドの領域を取る。
	listHead = (DL*)malloc(sizeof(DL));

	//リストヘッドの初期化
	//initialize(listHead);
	listHead = NULL;

	//命令数nの入力
	fgets(order, sizeof(order), stdin);
	sscanf(order, "%d", &n);

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

		//命令の入力
		fgets(order, sizeof(order), stdin);

		switch(strlen(order)){

			//deleteFirstの場合：
			case 12:
				deleteFirst();
				break;

			//deleteLastの場合：
			case 11:
				deleteLast();
				break;

			//それ以外の場合：
			default:
				sscanf(order, "%s %d\n", str, &key);

				//insertの場合
				if(strcmp(str, "insert") == 0){

					insert(key);

				}

				//deleteの場合
				else if(strcmp(str, "delete") == 0){

					delete(key);

				}

				//それ以外だった場合
				else{

					//printf("無効な入力です。\n");

				}

				break;

		}

		//displayAll(listHead);

	}

	displayAll(listHead);

	return 0;

}

void initialize(DL *p){

	p->prev = NULL;
	p->value = 0;
	p->next = NULL;

}

void displayAll(DL *p){

	if(p == NULL){

		return;

	}

	while(1){

		printf("%d", p->value);

		if(p->next == NULL){

			break;

		}
		else{

			printf(" ");

		}

		p = p->next;

	}

	printf("\n");

}

void insert(int key){

	DL *p = (DL*)malloc(sizeof(DL));
	p->prev = NULL;
	p->value = key;
	p->next = listHead;

	//リストヘッド（元）のprevに、今作ったポインタを繋げる
	if(size > 0){

		listHead->prev = p;

	}
	else{

		listHead = p;

	}

	//リストヘッドを更新する。
	listHead = p;

	size++;

}

void delete(int key){

	//リストヘッドからチェック開始
	DL *p;

	//最終的に削除できたかを管理
	int isDeleted = 0;

	while(1){

		//pの値がkeyと一致した場合：
		//if(p->value == key){
		if(listHead->value == key){

			//作業用の変数pにリストヘッドを移す
			p = listHead;

			//この時点でリストヘッドは先頭に戻る
			listHead = gotoHead(listHead);

			//1つ前の要素があるなら（＝最初の要素でなければ）、「1つ前の要素の、次の要素（＝今現在は自分が入っている）へのリンク」に、自分の次の要素を入れる（＝自分をスキップする形にする）
			if(p->prev != NULL){

				if(p->next != NULL){

					p->prev->next = p->next;

				}
				else{

					p->prev->next = NULL;

				}

			}

			//次の要素があるなら（＝最後の要素でなければ）、「1つ次の要素の、前の要素（＝今現在は自分が入っている）へのリンク」に、自分の前の要素を入れる（＝自分をスキップする形にする）」
			if(p->next != NULL){

				if(p->prev != NULL){

					p->next->prev = p->prev;

				}
				else{

					p->next->prev = NULL;

				}

			}

			//********************************************この時点で、1つ前からも1つ先からも、両方ともから自分はアクセスされない。	→	削除完了。******************************************

			//ついでにfreeでメモリ解放。
			free(p);

			//削除に成功した、という印。
			isDeleted = 1;

			//削除したらループを抜ける。s
			break;

		}

		//次の要素がもうない（＝最後の要素）の場合、ループを抜ける。
		//if(p->next == NULL){
		else if(listHead->next == NULL){

			break;

		}

		//現在地を1つ進める。
		//p = p->next;
		listHead = listHead->next;

	}

	//削除した場合とできなかった場合のメッセージ
	if(isDeleted){

		//printf("%d を削除しました\n\n", key);

	}
	else{

		//printf("%d は見つかりませんでした\n\n", key);

	}

	size--;

}

//リストの先頭の要素を削除する
void deleteFirst(void){

	//次の要素があったら、次の要素からの、自分へのリンクを切る。
	if(listHead->next != NULL){

		listHead->next->prev = NULL;

		//リストヘッドの更新
		listHead = listHead->next;

	}

	//次の要素がなかったら、自分をNULLにする。
	else{

		//
		listHead = NULL;

	}

	size--;

}

//リストの末尾の要素を削除する
void deleteLast(void){

	DL *p = listHead;

	while(p->next != NULL){

		p = p->next;

	}

	//printf("p->value = %d\n", p->value);

	//1つ前の要素があったら（＝要素が自分だけじゃなかったら）
	if(p->prev != NULL){

		//printf("p->prev->next->value = %d\n", p->prev->next->value);

		//1つ前の要素の、次の要素へのリンク（＝自分へのリンク）をNULLにする。（自分が最後の要素だから）
		p->prev->next = NULL;

		//printf("p->prev->next = %p\n", p->prev->next);

		//自分自身を消す。
		p = NULL;

	}
	else{

		p = NULL;

	}

	size--;

	//サイズが0になったら（＝要素が元々1つしかなく、それを今消したところだったら）、リストヘッドをNULLにする。
	if(size == 0){

		listHead = NULL;

	}

}

//リストの先頭まで戻る関数
DL* gotoHead(DL *p){

	while(p->prev != NULL){

		p = p->prev;

	}

	return p;

}


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

// 双方向連結リスト構造体
struct list {
    int key;
    struct list *prev;
    struct list *next;
};

struct list *first;
struct list *last;

void init(void)
{
    first = NULL;
    last = NULL;
}

// 連結リストの先頭からキー値を出力する
void disp(void)
{
    struct list *p = first;

    if ( p == NULL ) {
        return;
    }

    while ( 1 ) {
        printf("%d", p->key);
        if ( p == last ) {
            printf("\n");
        } else {
            printf(" ");
        }
        if ( p->next == NULL ) {
            break;
        }
        p = p->next;
    }
}

// 連結リストの先頭にキー x を持つ要素を継ぎ足す。
void insert(int x)
{
    struct list *li;

    li = (struct list*)malloc(sizeof(struct list));
    li->key = x;
    li->prev = NULL;
    li->next = NULL;

    //リスト空？
    if ( first == NULL ) {
        first = li;
        last = li;
    } else {
        first->prev = li;
        li->next = first;
        first = li;
    }
}

// リストの先頭の要素を削除する。
void deleteFirst(void)
{
    struct list *p;

    if ( first == last ) {
        free(first);
        init();
    } else {
        p = first->next;
        p->prev = NULL;
        free(first);
        first = p;
    }
}

// リストの末尾の要素を削除する。
void deleteLast(void)
{
    struct list *p;

    if ( first == last ) {
        free(last);
        init();
    } else {
        p = last->prev;
        p->next = NULL;
        free(last);
        last = p;
    }
}

// キー x を持つ最初の要素を連結リストから削除する。
// そのような要素が存在しない場合は何もしない。
void delete(int x)
{
    struct list *p;
    struct list *p1;
    struct list *p2;

    p = first;

    while( 1 ) {
        if ( p->key == x ) {
            // リストの位置ごとの処理
            if ( p == first ) {
                deleteFirst();
            } else if ( p == last ) {
                deleteLast();
            } else {
                // ポインタの繋ぎかえ
                p1 = p->prev;
                p1->next = p->next;
                p2 = p->next;
                p2->prev = p1;
                free(p);
            }
            break;
        }
        if ( p->next == NULL ) {
            break;
        }
        p = p->next;
    }
}

int main(void)
{
    int n;
    char line[256];
    char *tp;

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

    init();

    for ( int i = 0; i < n; i++ ) {
        memset(line ,'\0', sizeof(line));
        fgets(line, sizeof(line), stdin);
        tp = strtok(line, " \n");
        if ( strcmp(tp, "insert") == 0 ) {
            tp = strtok(NULL, "\n");
            insert(atoi(tp));
        } else if ( strcmp(tp, "deleteFirst") == 0 ) {
            deleteFirst();
        } else if ( strcmp(tp, "deleteLast") == 0 ) {
            deleteLast();
        } else {
            tp = strtok(NULL, "\n");
            delete(atoi(tp));
        }
    }

    disp();

    return 0;
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Doubly Linked List

Your task is to implement a double linked list.

Write a program which performs the following operations:

insert x: insert an element with key x into the front of the list.

delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything.

deleteFirst: delete the first element from the list.

deleteLast: delete the last element from the list.

Input

The input is given in the following format:

n

command1

command2

...

commandn

In the first line, the number of operations n is given. In the following n lines, the above mentioned operations are given in the following format:

insert x

delete x

deleteFirst

deleteLast

Output

Print all the element (key) in the list after the given operations. Two consequtive keys should be separated by a single space.

Constraints

The number of operations ≤ 2,000,000

The number of delete operations ≤ 20

0 ≤ value of a key ≤ 109

The number of elements in the list does not exceed 106

For a delete, deleteFirst or deleteLast operation, there is at least one element in the list.

Sample Input 1

7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5

Sample Output 1

6 1 2

Sample Input 2

9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast

Sample Output 2

1

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


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

struct node{
  int key;
  struct node *next;
  struct node *prev;
};

typedef struct node * NodePointer;

NodePointer nil;

NodePointer listSearch(int key){
  NodePointer n,t;
  n=nil;
  while(1){
    if(n->next==nil)return t;
    if(n->next->key==key)return n->next;
    n=n->next;
  }
}

void init(){
  nil = malloc(sizeof(struct node));
  nil->next = nil;
  nil->prev = nil;
}

void printList(){
  NodePointer cur = nil->next;
  int isf = 1;
  while(1){
    if ( cur == nil ) break;
    if ( isf == 0)  printf(" ");
    printf("%d", cur->key);
    cur = cur->next;
    isf = 0;
  }
  printf("\n");
}

void deleteNode(NodePointer t){
  t->prev->next = t->next;
  t->next->prev = t->prev;
  free(t);
}

void deleteFirst(){
  NodePointer t = nil->next;
  if ( t == nil ) return;
  deleteNode(t);
}

void deleteLast(){
  NodePointer t = nil->prev;
  if ( t == nil ) return;
  deleteNode(t);
}

void delete(int key){
  NodePointer t,n;
  t=listSearch(key);
  if(t==n)return ;
  deleteNode(t);
}

void insert(int key){
  NodePointer x;
  x = malloc(sizeof(struct node));
  x->key = key;
  x->next=nil->next;
  x->prev=nil;
  nil->next->prev= x;
  nil->next=x;
}

int main(){
  int key, n, i;
  int size = 0;
  char com[20];
  int np = 0, nd = 0;
  scanf("%d", &n);
  init();
  for ( i = 0; i < n; i++ ){
    scanf("%s", com);
    if ( com[0] == 'i' ) {
      scanf("%d",&key);
      insert(key);
      np++;
      size++;
    }else if ( com[0] == 'd' ) {
      if (strlen(com) > 6){
	if ( com[6] == 'F' ) deleteFirst();
	else if ( com[6] == 'L' ) deleteLast();
      } else {
	scanf("%d",&key);
	delete(key);
      }
    }
  }

  printList();
  return 0;
}


#include<stdio.h>

int n,S[100000];

int binarySearch(int);

int main(){
  int i, q, count=0, key, T[50000];

  scanf("%d",&n);
  for(i=0;i<n;i++)scanf("%d",&S[i]);
  scanf("%d",&q);
  for(i=0;i<q;i++)scanf("%d",&T[i]);

  for(i=0;i<q;i++){
    key=T[i];
    if(binarySearch(key)==1)count++;
  }
  printf("%d\n",count);

  return 0;
}

int binarySearch(int key){
  int left=0, right=n, mid;
  while(left<right){
    mid=(left+right)/2;
    if(S[mid]==key)return 1;
    else if(key>S[mid])left=mid+1;
    else right=mid;
  }
  return 0;
}

Search II

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

Elements in S is sorted in ascending order

n ≤ 100000

q ≤ 50000

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
1 2 3
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes


#include<stdio.h>

#define N 100000

int serch(int a[], int b, int key){
  int i;
  for(i=0;i<=b-1;i++){
    if(a[i] == key){
      return 1;
    }
  }
  return 0;
}

int main(){
  int n, q, i, j, count = 0, discount = 0;
  int S[N],T[N];

   scanf("%d",&n);

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

  scanf("%d",&q);

  for(i=0;i<=q-1;i++){
    scanf("%d",&T[i]);
  }
  for(i=0;i<=q-1;i++){
    if(serch(S,n,T[i]) == 1){
      count += 1;
    }
  }

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

  return 0;
}


#include <stdio.h>
int A[1000000], n;
int binarySearch(int key) {
  int left = 0;
  int right = n;
  int mid;
  while(left < right) {
    mid = (left + right) / 2;
    if(key == A[mid]) return 1;
    if(key > A[mid]) left = mid + 1;
    else if(key < A[mid]) right = mid;
  }
  return 0;
}
int main(void) {
  int i, q, k, sum = 0;
  scanf("%d",&n);
  for(i=0; i<n; i++) {
    scanf("%d",&A[i]);
  }
  scanf("%d",&q);
  for(i=0;i<q;i++) {
    scanf("%d",&k);
    if(binarySearch(k))
      sum++;
  }
  printf("%d\n",sum);
  return 0;
}


#include<stdio.h>

 int B(int n,int S[],int key){
      int i,right,left,mid;
      left=0;
      right=n;
      while(left<right){
             mid=(left+right)/2;
             if(S[mid]==key)return 1;
             else if(key<S[mid])right=mid;
             else left=mid+1;
             }
      return 0;
      }

 int main(){
      int i,j,n,q,S[100000],T,count=0,key;
      scanf("%d",&n);
      for(i=0;i<n;i++){
            scanf("%d",&S[i]);
            }
      scanf("%d",&q);
      for(i=0;i<q;i++){
            scanf("%d",&T);
            key=B(n,S,T);
            if(key!=0)count++;
            }
      printf("%d\n",count);
      return 0;
      }


#include <stdio.h>

#define N 20
#define Q 200

int n;
int A[N];

int solve(i, m) {
	if (m == 0) return 1;

	if (i >= n) return 0;

	if (solve(i+1, m) || solve(i+1, m-A[i])) return 1;

	return 0;
}

int main() {
	int i;
	int q;
	int M[Q];

	scanf("%d", &n);

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

	scanf("%d", &q);

	for (i = 0; i < q; i++)
		scanf("%d", &M[i]);

	for (i = 0; i < q; i++) {
		if (solve(0, M[i])) printf("yes\n");
		else printf("no\n");
	}

	return 0;
}

Exhaustive Search

Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.

You are given the sequence A and q questions where each question contains Mi.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers (Mi) are given.

Output

For each question Mi, print yes or no.

Constraints

n ≤ 20

q ≤ 200

1 ≤ elements in A ≤ 2000

1 ≤ Mi ≤ 2000

Sample Input 1

5
1 5 7 10 21
8
2 4 17 8 22 21 100 35

Sample Output 1

no
no
yes
yes
yes
yes
no
no

Notes

You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:

solve(0, M)

solve(1, M-{sum created from elements before 1st element})

solve(2, M-{sum created from elements before 2nd element})

...

The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.

For example, the following figure shows that 8 can be made by A[0] + A[2].


#include<stdio.h>
#define true 1
#define false -1

int solve(int,int);
int a[20],n;

int main(){
  int i,q,r;
  int m[200];

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

  scanf("%d",&q);
  for(i=0;i<q;i++) scanf("%d",&m[i]);

  for(i=0;i<q;i++){
    r=solve(0,m[i]);
    if(r==false) printf("no\n");
    else printf("yes\n");
  }
  return 0;
}

int solve(int i,int m){
  int res;
  if(m==0) return true;
  if(i>=n) return false;
  res=solve(i+1,m);
  if(res==false) res=solve(i+1,m-a[i]);
  return res;
}


#include<stdio.h>

int solve(int,int);

int q,n,A[2000],M[2000];

int main(){
  int i,j;

  //in
  scanf("%d", &n);
  for(i=0; i<n; i++){
    scanf("%d", &A[i]);
  }
  scanf("%d", &q);
  for(i=0; i<q; i++){
    scanf("%d", &M[i]);
  }

  //M[1~q]まで再帰にかける&out
  for(i=0; i<q; i++){
    if( solve(0, M[i]) ){
      printf("yes\n");
    }
    else{
      printf("no\n");
    }
  }
  return 0;
}

int solve(int i,int m){
  //(M[]の内1項)−(分岐点の数値)=0ならその数値になり得る
  if(m-A[i]==0) return 1;
  //A[]の要素数を超えるとmになりえない
  if(i >= n) return 0;
  //まだ判断ができない場合はsolveに再帰的に変数値を引き継ぐ
  if(solve(i+1,m-A[i]) || solve(i+1,m)) return 1;
  return 0;
}


#include <stdio.h>
#include <stdlib.h>
/*#include <math.h> INFINITY*/

#define MAX 500000
#define INFINITY 1000000001

void mergeSort(int *, int, int);
void merge(int *, int, int, int);

int L[MAX / 2 + 2], R[MAX / 2 + 2];
int count = 0;

int main(){
  int *A, n, i;
  scanf("%d",&n);
  A = malloc(n * sizeof(int));
  for(i = 0; i < n; i++){
    scanf("%d",&A[i]);
  }
  mergeSort(A, 0, n);
  for(i = 0; i < n - 1; i++){
    printf("%d ",A[i]);
  }
  printf("%d\n",A[n - 1]);
  printf("%d\n",count);

  return 0;
}

void mergeSort(int *A, int left, int right){
  int mid;
  if(left + 1 != right){
    mid = (left + right) / 2;
    mergeSort(A, left, mid);
    mergeSort(A, mid, right);
    merge(A, left, mid, right);
  }
}
void merge(int *A, int left, int mid, int right){
  int i, j, k;
  int n1 = mid - left;
  int n2 = right - mid;
  for(i = 0; i < n1; i++){
    L[i] = A[left + i];
  }
  for(i = 0; i < n2; i++){
    R[i] = A[mid + i];
  }
  L[n1] = INFINITY;
  R[n2] = INFINITY;
  i = 0;
  j = 0;
  for(k = left; k < right; k++){
    count++;
    if(L[i] <= R[j]){
      A[k] = L[i++];
    }
    else{
      A[k] = R[j++];
    }
  }
}

Merge Sort

Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.

Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] = A[mid + i]
L[n1] = SENTINEL
R[n2] = SENTINEL
i = 0;
j = 0;
for k = left to right-1
if L[i] <= R[j]
then A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1

Merge-Sort(A, left, right){
if left+1 < right
then mid = (left + right)/2;
call Merge-Sort(A, left, mid)
call Merge-Sort(A, mid, right)
call Merge(A, left, mid, right)

Input

In the first line n is given. In the second line, n integers are given.

Output

In the first line, print the sequence S. Two consequtive elements should be separated by a space character.

In the second line, print the number of comparisons.

Constraints

n ≤ 500000

0 ≤ an element in S ≤ 109

Sample Input 1

10
8 5 9 2 6 3 7 1 10 4

Sample Output 1

1 2 3 4 5 6 7 8 9 10
34

Notes


   #include <stdio.h>
    #define MAX 500001
    #define INFTY 100000000
    int A[MAX],L[MAX],R[MAX];
    int c=0;

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

      mergesort(A,0,n);

      for(i=0;i<n;i++){
        printf("%d",A[i]);
        if(i<n-1){
          printf(" ");
    }
}
printf("\n%d\n",c);

return 0;

    }

    void merge(int A[], int left, int mid, int right){

      int n1,n2,i,j,k;

    n1 = mid - left;

    n2 = right - mid;

    for(i=0;i<n1;i++){
      L[i]=A[left+i];
     }
    for(i=0;i<n2;i++){
      R[i]=A[mid+i];
     }

      L[n1]=INFTY;
      R[n2]=INFTY;
       i=0;
      j=0;

    for(k=left;k<right;k++){
      c++;
      if(L[i]<=R[j]){
        A[k]=L[i];
        i=i+1;
      }
      else{
                A[k]=R[j];
            j=j+1;
         }
        }
        }

    void mergesort(int A[],int left,int right){
      int mid;
      if(left+1<right){
        mid = (left + right)/2;
           mergesort(A,left,mid);
        mergesort(A,mid,right);
        merge(A,left, mid, right);
          }
    }


#include <stdio.h>
int count=0,n;
void MergeSort(int x[],int left,int right){
  int mid,i,j,k,temp[n];
  if(left>=right) return;
  mid=(left+right)/2;
  MergeSort(x,left,mid);
  MergeSort(x,mid+1,right);
  for(i=left;i<=mid;i++){
    temp[i]=x[i];
  }
  for(i=mid+1,j=right;i<=right;i++,j--){
    temp[i]=x[j];
  }
  i=left;
  j=right;
  for(k=left;k<=right;k++){
    if(temp[i]<=temp[j]){
      x[k]=temp[i++];
    }
    else x[k]=temp[j--];
    count++;
  }
}
int main(){
  int i;
  scanf("%d",&n);
  int x[n];
  for(i=0;i<n;i++){
    scanf("%d",&x[i]);
  }
  MergeSort(x,0,n-1);
  for(i=0;i<n;i++){
    printf("%d",x[i]);
    if(i!=n-1){
      printf(" ");
    }
  }
  printf("\n%d\n",count);
  return 0;
}


#include <stdio.h>
#define max 500000
int L[max/2+2];
int R[max/2+2];
int c=0;
int merge(int S[], int n, int left, int mid, int right){
int i, j, k;
int n1 = mid-left;
int n2 = right-mid;
for (i = 0; i < n1; i++)
L[i] = S[left+i];
for (i = 0; i < n2; i++)
R[i] = S[mid+i];
L[n1] = R[n2] = 2000000000;
i = j = 0;
for ( k = left; k < right; k++){
c++;
if ( L[i] <= R[j]){
S[k] = L[i];
i++;
}
else{
S[k] = R[j];
j++;
}
}
}
void mergeSort(int S[], int n, int left, int right){
int mid;
if (left+1<right){
mid = (left+right) / 2;
mergeSort(S,n, left,mid);
mergeSort(S, n,mid,right);
merge(S,n, left,mid,right);
}
}
int main(){
int S[max], n, i;

scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &S[i]);
mergeSort(S, n, 0, n);
for (i = 0; i < n; i++){
if(i==0)
printf("%d", S[i]);
else
printf(" %d", S[i]);
}

printf("\n");

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

return 0;
}


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

void printArray(int,int[]);
int merge(int,int[],int,int,int);
int merge_sort(int,int[],int,int);

int main(int argc, char** argv) {
    int size;
    scanf("%d\n", &size);
    int array[size];
    for(int i = 0; i < size; i++)
        scanf("%d", &array[i]);

    int returnVal = merge_sort(size, array, 0, size);
    printArray(size, array);
    printf("%d\n", returnVal);

    return (EXIT_SUCCESS);
}

int merge(int size, int a[size], int left, int mid, int right){
    int count = 0;
    int i = 0;
    int j = 0;
    int n1 = mid - left;
    int n2 = right - mid;
    int lArray[n1], rArray[n2];
    for(; i < n1; i++)
        lArray[i] = a[left + i];
    for(; j < n2; j++)
        rArray[j] = a[mid + j];
    i = 0;
    j = 0;
    for(int k = left; k < right; k++){
        if(i < n1 && lArray[i] <= rArray[j] || j >= n2)
            a[k] = lArray[i++];
        else
            a[k] = rArray[j++];
        count++;
    }
    return count;
}

int merge_sort(int size, int a[size], int left, int right){
    int count = 0;
    if(left+1 < right){
        int mid = (left + right)/2;
        count += merge_sort(size, a, left, mid);
        count += merge_sort(size, a, mid, right);
        count += merge(size, a, left, mid, right);
        //printArray(size, a);
    }
    return count;
}

void printArray(int size, int a[size]){
    for(int i = 0; i < size; i++){
        if(i != size - 1)
            printf("%d ", a[i]);
        else printf("%d\n", a[i]);
    }
}


#include<stdio.h>
int count = 0;
int L[500000];
int R[500000];

void merge(int *A,int left ,int mid ,int right){
int n1,n2,i,j,k;

n1 = mid - left;
n2 = right - mid;

for(i=0;i < n1; i++){
L[i] = A[left + i];
}
for(i=0;i < n2; i++){
R[i] = A[mid + i];
}

L[n1] = 1000000000;
R[n2] = 1000000000;

i=0;
j=0;

for(k = left ; k < right ; k++){

if(L[i]<= R[j]){
A[k]=L[i];
i = i+1;
count++;
}
else{
    A[k]=R[j];
    j=j+1;
count++;
}

}
}

void mergeSort(int *A,int left ,int right){
    int mid;
if((left + 1) < right){
 mid = (left + right) / 2;
  mergeSort(A,left,mid);
  mergeSort(A,mid,right);
  merge(A,left,mid ,right);

}

}
int main(){

int n,i,left,right;
int S[500000];

scanf("%d",&n);

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

    scanf("%d",&S[i]);
}
left = 0;
right = n;

mergeSort(S,left,right);

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

printf("%d",S[i]);

if(i+1 != n)
printf(" ");
}
printf("\n%d\n",count);
return 0;
}


#include<stdio.h>
#include<stdlib.h>
int merge(int *S,int left,int mid,int right,int count){
    int n1,n2,i,j,k;
    double *L,*R;
    n1=mid-left;
    n2=right-mid;
    L=malloc(sizeof(double)*(n1+1));
    R=malloc(sizeof(double)*(n2+1));
    for(i=0;i<n1;i++){
        *(L+i)=*(S+left+i);
    }
    for(i=0;i<n2;i++){
        *(R+i)=*(S+mid+i);
    }
    *(L+n1)=10000000000;
    *(R+n2)=10000000000;

    i=0; j=0;
    for(k=left;k<right;k++){
        if(*(L+i)<=*(R+j)){
            *(S+k)=*(L+i);
            i=i+1;
            count++;
        }
        else{
            *(S+k)=*(R+j);
            j=j+1;
            count++;
        }
    }
    free(L);
    free(R);
    return count;
}

int mergeSort(int *S, int left,int right,int count){
    int mid;
    if((left+1)<right){
        mid=(left+right)/2;
        count=mergeSort(S,left,mid,count);
        count=mergeSort(S,mid,right,count);
        count=merge(S,left,mid,right,count);
    }
    return count;
}
int main(void){
    int n,*S,i,count=0;
    scanf("%d",&n);
    S=malloc(sizeof(int)*n);
    for(i=0;i<n;i++){
        scanf("%d",(S+i));
    }
    count=mergeSort(S,0,n,count);
    for(i=0;i<n-1;i++){
        printf("%d ",*(S+i));
    }
    printf("%d\n",*(S+i));
    printf("%d\n",count);
    free(S);
    return 0;
}


#include<stdio.h>
#include<limits.h>

int compTimes = 0;

void merge(int A[], int left, int mid, int right){
	int n1 = mid - left;
	int n2 = right - mid;
	int L[n1+1], R[n2+1];
	int i, j, k;
	for( i = 0; i < n1; i++ ){ L[i] = A[left+i]; }
	for( i = 0; i < n2; i++ ){ R[i] = A[mid+i]; }
	L[n1] = INT_MAX;
	R[n2] = INT_MAX;
	i = 0;
	j = 0;
	int c = 0;
	for( k = left; k < right; k++ ){
		if( L[i] <= R[j] ){
			A[k] = L[i++];
			c++;
		}else{
			if( c < n1 ){ compTimes += n1 - c; }
			A[k] = R[j++];
		}
	}
	return;
}

void mergeSort(int A[], int left, int right){
	if( left+1 <  right ){
		int mid = (left + right) / 2;
		mergeSort(A, left, mid);
		mergeSort(A, mid, right);
		merge(A, left, mid, right);
	}
	return;
}

int main(){
	int A[200000], S[200000];
	int n, i, j, count = 0;
	scanf("%d", &n);
	for( i = 0; i < n; i++ ){
		scanf("%d", &A[i]);
		S[i] = A[i];
	}
	mergeSort(S, 0, n);
	printf("%d\n", compTimes);
	return 0;
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

The Number of Inversions

For a given sequence $A = \{a_0, a_1, ... a_{n-1}\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program:

bubbleSort(A)
cnt = 0 // the number of inversions
for i = 0 to A.length-1
for j = A.length-1 downto i+1
if A[j] < A[j-1]
swap(A[j], A[j-1])
cnt++

return cnt

For the given sequence $A$, print the number of inversions of $A$. Note that you should not use the above program, which brings Time Limit Exceeded.

Input

In the first line, an integer $n$, the number of elements in $A$, is given. In the second line, the elements $a_i$ ($i = 0, 1, .. n-1$) are given separated by space characters.

output

Print the number of inversions in a line.

Constraints

$ 1 \leq n \leq 200,000$

$ 0 \leq a_i \leq 10^9$

$a_i$ are all different

Sample Input 1

5
3 5 2 1 4

Sample Output 1

6

Sample Input 2

3
3 1 2

Sample Output 2

2


#include<stdio.h>

#define MAX 500000
#define SENTINEL 2000000000
typedef long long llong;

int L[MAX/2+2],R[MAX/2+2];

llong merge(int a[MAX],int left,int mid,int right){
	int i,j,k;
	llong cnt=0;
	int n1=mid-left;
	int n2=right-mid;
	for(i=0;i<n1;i++)L[i]=a[left+i];
	for(i=0;i<n2;i++)R[i]=a[mid+i];
	L[n1]=R[n2]=SENTINEL;
	i=0;
	j=0;
	for(k=left;k<right;k++){
		if(L[i]<=R[j]){
			a[k]=L[i++];
		}
		else{
			a[k]=R[j++];
			cnt+=n1-i;
		}
	}

	return cnt;
}

llong mergeSort(int a[MAX],int left,int right){
	llong v1,v2,v3;
	if(left+1<right){
		int mid=(left+right)/2;
		v1=mergeSort(a,left,mid);
		v2=mergeSort(a,mid,right);
		v3=merge(a,left,mid,right);
		return v1+v2+v3;
	}else return 0;
}

int main(void){
	int a[MAX],n;

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

	llong ans=mergeSort(a,0,n);

	printf("%lld\n",ans);

	return 0;
}


#include  <stdio.h>
#define MAX 2000001

int A[MAX],B[MAX],C[MAX];

void ShowData(int n)
{
  int i;
  for (i = 1; i <= n ; i++){
    printf("%u", B[i]);
    if(i<n)printf(" ");
  }
  printf("\n");
}

void CountingSort( int n)
{
  int i, j, k;

  for (i=0;i<=MAX;i++)
  C[i] = 0;

  for (j=1;j<=n;j++){
    scanf("%d",&A[j]);
    C[A[j]]++;

  }
  for (i=1;i<=MAX;i++) {
    C[i] += C[i-1];
  }
  for (j=n;j>0;j--) {
    B[C[A[j]]] = A[j];
    C[A[j]]--;
    }

}

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

   CountingSort(n);
   ShowData(n);
  return 0;
}

Counting Sort

Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:

Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1

Write a program which sorts elements of given array ascending order based on the counting sort.

Input

The first line of the input includes an integer n, the number of elements in the sequence.

In the second line, n elements of the sequence are given separated by spaces characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

Constraints

1 ≤ n ≤ 2,000,000

0 ≤ A[i] ≤ 10,000

Sample Input 1

7
2 5 1 3 2 3 0

Sample Output 1

0 1 2 2 3 3 5


#include <stdio.h>
#include <stdlib.h>
#define NMAX 2000000
#define AMAX 10000
int n=AMAX;
void CountingSort(unsigned short *,unsigned short *,int);
int main(){
  int i;
  unsigned short *A;
  unsigned short *B;
  int k;

  scanf("%d",&k);

  A=malloc(sizeof(short)*k+1);
  B=malloc(sizeof(short)*k+1);

  for(i=0;i<k;i++){
    scanf("%hu",&A[i+1]);
  }
  //  printf("ok1\n");
  CountingSort(A,B,k);
  return 0;
}

void CountingSort(unsigned short *A,unsigned short *B,int k){
  int i,j;
  int C[AMAX+1];
  //printf("ok2\n");
  for(i=0;i<=AMAX;i++){
    C[i]=0;
  }
  //printf("ok3\n");
  for(j=0;j<k;j++){
    C[A[j+1]]++;
  }
  //printf("ok4\n");
  for(i=1;i<=AMAX;i++){
    C[i]=C[i]+C[i-1];
  }
  //printf("ok5\n");
  for(j=1;j<=k;j++){
    B[C[A[j]]]=A[j];
    C[A[j]]--;
  }
  //printf("ok6\n");
  for(i=1;i<=k;i++){
    if(i>1)
      printf(" ");
    printf("%d",B[i]);
  }
  printf("\n");
}


#include <stdio.h>
#define N 20000000

int A[N], B[N], C[N], n;

 int main()
{

  int i;
  int max=0;

  scanf("%d",&n);

  for(i = 1;i <= n;i++)
    {
      scanf("%d", &B[i]);
      if(max< B[i])
    {
      max = B[i];
    }
    }

  CountingSort(max);

  for(i = 1;i <= n;i++)
    {
      if(i > 1) printf(" ");
      printf("%d",C[i]);
    }
  printf("\n");
  return 0;
}
 void CountingSort(int k)
{
  int i, j;
  for(i = 0; i <= k; i++)
    {
      A[i] = 0;
    }
  for(j = 1;j <= n;j++)
    {
      A[B[j]]++;
    }
  for(i = 1;i <= k;i++)
    {
      A[i] = A[i] + A[i - 1];
    }
  for(j = n;j > 0;j--)
    {
      C[A[B[j]]] = B[j];
      A[B[j]]--;
    }
}


#include <stdio.h>
#include <stdlib.h>
#define MAX 2000001
#define VMAX 10000

int main(){
  unsigned short *A, *B;

  int C[VMAX+1];
  int n, i, j;
  scanf("%d", &n);

  A = malloc(sizeof(short)*n+1);
  B = malloc(sizeof(short)*n+1);

  for ( i = 0; i <= VMAX; i++ ) C[i] = 0;

  for ( i = 0; i < n; i++ ){
    scanf("%hu", &A[i + 1]);
    C[A[i + 1]]++;
  }

  for ( i = 1; i <= VMAX; i++ ) C[i] = C[i] + C[i - 1];

  for ( j = 1; j <= n; j++ ){
    B[C[A[j]]] = A[j];
    C[A[j]]--;
  }

  for ( i = 1; i <= n; i++ ){
    if ( i > 1 ) printf(" ");
    printf("%d", B[i]);
  }
  printf("\n");

  return 0;
}


#include<stdio.h>
#include<stdlib.h>
#define MAX 2000001
#define VMAX 10000

int main() {
    unsigned short *A, *B;

    int C[VMAX+ 1];
    int n, i, j;
    scanf("%d", &n);

    A = malloc(sizeof(short) * n + 1);
    B = malloc(sizeof(short) * n + 1);

    for (i=0; i<=VMAX; i++) C[i]=0;

    for (i=0; i<n; i++) {
        scanf("%hu", &A[i+1]);
        C[A[i + 1]]++;
    }

    for (i=1; i<=VMAX; i++) C[i] = C[i] + C[i-1];

    for (j=1; j<=n; j++) {
        B[C[A[j]]] = A[j];
        C[A[j]]--;
    }

    for (i=1; i<=n; i++) {
        if (i>1) printf(" ");
        printf("%d", B[i]);
    }
    printf("\n");

    return 0;
}


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

int partition(int*, int);

int main() {
  int i, n, key;
  int *a;

  scanf("%d",&n);
  a = (int*)malloc(sizeof(int) * n);
  for(i = 0;i < n;i++)
    scanf("%d",&a[i]);
  key = partition(a, n);
  for(i = 0;i < n;i++) {
    if(i == key) printf("[%d]",a[i]);
    else printf("%d",a[i]);
    if(i != n-1) printf(" ");
  }
  printf("\n");
  free(a);
  return 0;
}

int partition(int* a, int r) {
  int j, change;
  int x = a[r-1];
  int i = -1;
  int k;
  for(j = 0;j < r-1;j++) {
    if(a[j] <= x) {
      i++;
      change = a[i];
      a[i] = a[j];
      a[j] = change;
    }
  }
  change = a[i+1];
  a[i+1] = a[r-1];
  a[r-1] = change;
  return i+1;
}

Partition

Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. It also computes the index q.

In the conquer processes, the two subarrays A[p..q-1] and A[q+1..r] are sorted by recursive calls of QuickSort(A, p, q-1) and QuickSort(A, q+1, r).

Your task is to read a sequence A and perform the Partition based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1

Note that, in this algorithm, Partition always selects an element A[r] as a pivot element around which to partition the array A[p..r].

Input

The first line of the input includes an integer n, the number of elements in the sequence A.

In the second line, Ai (i = 1,2,...,n), elements of the sequence are given separated by space characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. The element which is selected as the pivot of the partition should be indicated by [  ].

Constraints

1 ≤ n ≤ 100,000

0 ≤ Ai ≤ 100,000

Sample Input 1

12
13 19 9 5 12 8 7 4 21 2 6 11

Sample Output 1

9 5 8 7 4 2 6 [11] 21 13 19 12


#include<stdio.h>
#define MAX 1000000
int Partition(int *,int,int);

int A[MAX],key;
main(){
  int n,i;
  scanf("%d",&n);
  for(i=1;i<=n;i++){
    scanf("%d",&A[i]);

  }

  key = Partition(A,0,n);

  for(i = 1; i < key; i++){
    printf("%d ",A[i]);
  }
  printf("[%d] ",A[key]);
  for(i = key+1;i<=n;i++){
    if(i == n){
      printf("%d\n",A[n]);
    }else{
      printf("%d ",A[i]);
    }
  }

  return 0;
}

int Partition(int *A,int p,int r){
  int i,j,x,tmp;
  x = A[r];
  i = p-1;
  for(j = p; j < r; j++){
    if(A[j] <= x){
      i++;

      tmp = A[i];
      A[i] = A[j];
      A[j] = tmp;
    }
  }
  tmp = A[r];
  A[r] = A[i+1];
  A[i+1] = tmp;

  return i+1;

}


#include <stdio.h>
#define N 1000001

int Partition(int, int );
int A[N];

int main(void){
int i,n,y;

 scanf("%d",&n);

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

 y=Partition(1,(n));

 for(i=1;i<n;i++){

   if (i==y){
     printf("[%d] ",A[i]);
   }
   else printf("%d ",A[i]);
 }

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

 return 0;

}

int Partition(int p, int r){
  int i, j, x, k;

  x=A[r];
  i=p-1;
  for(j=p;j<=r-1;j++){

    if(A[j]<=x){
      i++;
      k=A[i];
      A[i]=A[j];
      A[j]=k;
    }

  }
  k=A[i+1];
  A[i + 1] = A[r];
  A[r]=k;
  return i+1;

}


#include<stdio.h>

int partition(int *, int,int);

int main(){
  int i,n,A[100000],par;

  scanf("%d",&n);

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

  par=partition(A,0,i-1);

  for(i=0;i<n-1;i++){
    if(i==par)
      printf("[%d] ",A[i]);

    else
      printf("%d ",A[i]);
  }

  printf("%d\n",A[i]);

  return 0;
}

int partition(int * A, int p,int r){
  int x,i,j,a;
  x=A[r];
  i=p-1;
  for(j=p;j<r;j++){
    if (A[j] <= x){
      i = i+1;
      a=A[i];
      A[i]=A[j];
      A[j]=a;
    }
  }

  a=A[i+1];
  A[i+1]=A[r];
  A[r]=a;

  return i+1;
}


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

typedef struct{
  int parent;//parent
  int left;//left child
  int right;//right sibling
}Tree;

int main(){
  Tree *t;
  int n,i,j,id,k,prov,depth,tn; //k=degree,prov=karinohensu,tn=type_number
  char type[3][15]={"root","internal node","leaf"};
  scanf("%d",&n);
  t=(Tree*)malloc(sizeof(Tree)*n);//akekata

  for(i=0;i<n;i++){
    t[i].parent=-1;
    t[i].left=-1;
    t[i].right=-1;
  }

  for(i=0;i<n;i++){
    scanf("%d",&id);
    scanf("%d",&k);
    for(j=0;j<k;j++){
      if(j==0){
	scanf("%d",&t[id].left);
	prov=t[id].left;
      }
      else{
	scanf("%d",&t[prov].right);
	  prov=t[prov].right;
      }
	  t[prov].parent=id;
    }
  }

  for(i=0;i<n;i++){
    //depth
    depth=0;
    prov=t[i].parent;
    while(prov!=-1){
      prov=t[prov].parent;
      depth++;
    }    //end of deptp
    //type
    if(depth==0)
      tn=0;
    else if(t[i].left==-1)
      tn=2;
    else
      tn=1;
    //ende of type
    printf("node %d: parent = %d, depth = %d, ",i,t[i].parent,depth);
    printf("%s, [",type[tn]);
    if(t[i].left!=-1)
      {
	printf("%d",t[i].left);
	prov=t[i].left;
	while(t[prov].right!=-1){
	  printf(", %d",t[prov].right);
	  prov=t[prov].right;
	}
      }
    printf("]\n");
  }
  free(t);
  return 0;
}

Rooted Trees

A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).

Fig. 1

A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."

Your task is to write a program which reports the following information for each node u of a given rooted tree T:

node ID of u

parent of u

depth of u

node type (root, internal node or leaf)

a list of chidlren of u

If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.

A node with no children is an external node or leaf. A nonleaf node is an internal node

The number of children of a node x in a rooted tree T is called the degree of x.

The length of the path from the root r to a node x is the depth of x in T.

Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.

Fig. 2

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of each node u is given in the following format:

id k c1 c2 ... ck

where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.

Output

Print the information of each node in the following format ordered by IDs:

node id: parent = p, depth = d, type, [c1...ck]

p is ID of its parent. If the node does not have a parent, print -1.

d is depth of the node.

type is a type of nodes represented by a string (root, internal node or leaf). If the root can be considered as a leaf or an internal node, print root.

c1...ck is the list of children as a ordered tree.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 100000

Sample Input 1

13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0

Sample Output 1

node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []

Sample Input 2

4
1 3 3 2 0
0 0
3 0
2 0

Sample Output 2

node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []

Note

You can use a left-child, right-sibling representation to implement a tree which has the following data:

the parent of u

the leftmost child of u

the immediate right sibling of u

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


#include<stdio.h>
#define MAX 100005
#define NIL -1
struct Node_struct{int p, l, r;}; /*p: 親(parent), l: 一番左の子(left child), r:右の兄弟(right sibling)*/
typedef struct Node_struct Node;
Node T[MAX];
int D[MAX];

void print(int u){
 int i, c;
 printf("node %d: parent = %d, depth = %d, ", u, T[u].p, D[u]);

 if(T[u].p == NIL) printf("root, ");
 else if(T[u].l == NIL) printf("leaf, ");
 else printf("internal node, ");

 printf("[");
 for (i=0, c = T[u].l; c != NIL; i++, c = T[c].r){
    if(i) printf(", ");
 printf("%d", c);
 }
  printf("]\n");

}

void calcDepth(int u, int p){
  D[u] = p;
  if(T[u].l != NIL) calcDepth(T[u].l,p+1);
  if(T[u].r != NIL) calcDepth(T[u].r,p);
}

int main(){
  int i, j, k;
  int n;
  int id, sib, child;
  int root = NIL;
  scanf("%d", &n);
  for(i=0; i<n; i++) T[i].p = T[i].l = T[i].r = NIL;

  for(i=0; i<n; i++){
    scanf("%d %d", &id, &k);
    for(j = 0, sib = NIL; j<k; j++){ //子を入力する (input children)
      scanf("%d", &child);
      T[child].p = id;
      if(j == 0) T[id].l = child; //idの一番左の子 (the most left child of id)
      else T[sib].r = child; //左の兄弟に繋げる (connect to left sibling)
      sib = child;//次の子供の左の兄弟 (the left sibling of the next child)
      }
    }

  //根を求める (find the root)
     for(i=0; i<n; i++){
    if(T[i].p == -1) root = i;
    }

  //それぞれのノードの深さを求める (find depth of each node)
        calcDepth(root, 0);

  //出力 (output)
          for(i=0; i<n; i++) print(i);

  return 0;
}


#include <stdio.h>
#include <stdlib.h>
#define MAX 100005
#define NIL -1

typedef struct Node{
  int dim;
  int *child;
  int p;
  int dep;
} node;

node tree[MAX];
void calcDep(int r){
  int i;
  for(i=0;i<tree[r].dim;i++){
    tree[tree[r].child[i]].dep+=1+tree[r].dep;

    calcDep(tree[r].child[i]);
  }
}

int main(){
  int n,i,j,k;
  scanf("%d",&n);
  for(i=0;i<n;i++){
    tree[i].p=NIL;
    tree[i].dep=0;
  }
  for(k=0;k<n;k++){
    scanf("%d",&i);
    scanf("%d",&tree[i].dim);
    tree[i].child=(int *)malloc(sizeof(int)*tree[i].dim);
    for(j=0;j<tree[i].dim;j++){
      scanf("%d",&tree[i].child[j]);
      tree[tree[i].child[j]].p=i;
    }
  }
  for(i=0;i<n;i++){
    if(tree[i].p==NIL) k=i;
  }
  calcDep(k);
  for(i=0;i<n;i++){
    printf("node %d: parent = %d, depth = %d, ",i,tree[i].p,tree[i].dep);
    if(tree[i].p==NIL){
      printf("root, [");
      for(j=0;j<tree[i].dim;j++){
	printf("%d",tree[i].child[j]);
	if(j!=tree[i].dim-1) printf(", ");
      }
    }
    else if(tree[i].dim==0){
      printf("leaf, [");
    }
    else{
      printf("internal node, [");
      for(j=0;j<tree[i].dim;j++){
	printf("%d",tree[i].child[j]);
	if(j!=tree[i].dim-1) printf(", ");
      }
    }
    printf("]\n");
  }
  return 0;
}


#include <stdio.h>

struct Node{
  int key;
  int pa,le,ri;
  int s,deg,dep,h;
  int type; //0:root 1:internal node 2:leaf
};
struct Node node[30];
int find(int a);
int height(int a);
int main(){
  int i,j,n;
  int ns,nh;
  int root,count;
  for(i=0;i<30;i++) node[i].pa=-1;
  scanf("%d",&n);
  for(i=0;i<n;i++){
    scanf("%d %d %d",&node[i].key,&node[i].le,&node[i].ri);
    //keyでpaを探す
    for(j=0;j<i;j++){
      if(node[i].key==node[j].le||node[i].key==node[j].ri){
        node[i].pa=node[j].key;   break;
      }
      if(node[i].le==node[j].key||node[i].ri==node[j].key){
        node[j].pa=node[i].key;   break;
      }
    }
  }
  //type
  for(i=0;i<n;i++){
    if(node[i].pa==-1){
      root=i; node[i].type=0;
    }else if(node[i].le==-1&&node[i].ri==-1)  node[i].type=2;
    else  node[i].type=1;
  }
  //sibling
  for(i=0;i<n;i++){
    if(node[i].pa==-1)  node[i].s=-1;
    else{
      ns=find(node[i].pa);
      if(node[ns].le==node[i].key)  node[i].s=node[ns].ri;
      else if(node[ns].ri==node[i].key) node[i].s=node[ns].le;
    }
  }
  //degree
  for(i=0;i<n;i++){
    if(node[i].le==-1&&node[i].ri==-1)  node[i].deg=0;
    else if(node[i].le==-1||node[i].ri==-1)   node[i].deg=1;
    else  node[i].deg=2;
  }
  //depth
  for(i=0;i<n;i++){
    count=0;  nh=i;
    while(node[nh].type!=0){
      count++;
      nh=find(node[i].pa);
    }
    node[i].dep=count;
  }
  //height
  for(i=0;i<n;i++){
    node[i].h=height(i);
  }
  //print
  for(i=0;i<n;i++){
    printf("node %d: parent = %d , sibling = %d , degree = %d, depth = %d, height = %d, ",node[i].key,node[i].pa,node[i].s,node[i].deg,node[i].dep,node[i].h);
    if(node[i].type==0) printf("root\n");
    else if(node[i].type==1)  printf("internal node\n");
    else  printf("leaf\n");
  }
  return 0;
}

int find(int a){
  int ans,i;
  for(i=0;i<30;i++){
    if(node[i].key==a){
      ans=i;  break;
    }
  }
  return ans;
}

int height(int a){
  if(node[a].type==2) return 0;
  else{
    if(height(find(node[a].le))<height(find(node[a].ri))) return 1+height(find(node[a].ri));
    else  return 1+height(find(node[a].le));
  }
}

Binary Tree

A rooted binary tree is a tree with a root node in which every node has at most two children.

Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:

node ID of u

parent of u

sibling of u

the number of children of u

depth of u

height of u

node type (root, internal node or leaf)

If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).

The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.

Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of each node is given in the following format:

id left right

id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.

Output

Print the information of each node in the following format:

node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type

p is ID of its parent. If the node does not have a parent, print -1.

s is ID of its sibling. If the node does not have a sibling, print -1.

deg, dep and h are the number of children, depth and height of the node respectively.

type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 25

Sample Input 1

9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1

Sample Output 1

node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define NIL NULL

struct node{
  int key;
  struct node *left;
  struct node *right;
  struct node *p;
};

typedef struct node * Node;

Node root;

/*宣言*/
void Inorder_tree_walk(Node);
void Preorder_tree_walk(Node);
void insert(int);
void find(Node,int);

/*main関数*/
int main(){
  int i,x,num;
  char s[10];
  int check;

  scanf("%d",&num);
  for (i=0; i<num; i++){
    scanf("%s",s);

    if (strcmp("insert",s)==0){
      scanf("%d",&x);
      insert(x);
    }

    if  (strcmp("print",s)== 0){
      Inorder_tree_walk(root);
      puts("");

      Preorder_tree_walk(root);
      puts("");
    }

    if(strcmp("find",s)==0){
      scanf("%d",&x);
      find(root,x);

      }
  }
  return 0;
}

/*先行順巡回*/
void Preorder_tree_walk(Node tree){
  printf(" %d",tree->key);
  if(tree != NIL){
    if((tree->left) != NIL)Preorder_tree_walk(tree->left);
    if((tree->right) != NIL)Preorder_tree_walk(tree->right);
  }
}

/*中間順巡回*/
void Inorder_tree_walk(Node tree){

  if(tree != NIL){

    if((tree->left) != NIL){Inorder_tree_walk(tree -> left);}

    printf(" %d",tree->key);

    if(tree->right!=NIL){Inorder_tree_walk(tree->right);}
  }
}

/*挿入*/
void insert(int k){
 Node y=NIL;
 Node x=root;
 Node z;

 /*新しいkeyの初期化*/
    z = malloc(sizeof(struct node));
    z->key=k;
    z->left=NIL;
    z->right=NIL;

     while(x!=NIL){
       y=x;
       if(z->key < x->key) x=x->left;
       else x=x->right;
     }
     z->p=y;

     if(y == NIL) root=z;
     else if((z->key) < (y->key)) y->left=z;
     else y->right=z;
}

 void find(Node tree, int k){

   while (tree != NIL && k != tree->key){

     if(k < tree->key) tree = tree->left;
     else tree=tree->right;
   }
   if( tree==NIL)puts("no");
   if( tree!=NIL)puts("yes");
 }

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Binary Search Tree I

Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.

Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

The following figure shows an example of the binary search tree.

For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2 y = NIL // parent of x
3 x = 'the root of T'
4 while x ≠ NIL
5 y = x // set the parent
6 if z.key < x.key
7 x = x.left // move to the left child
8 else
9 x = x.right // move to the right child
10 z.p = y
11
12 if y == NIL // T is empty
13 'the root of T' = z
14 else if z.key < y.key
15 y.left = z // z is the left child of y
16 else
17 y.right = z // z is the right child of y

Write a program which performs the following operations to a binary search tree $T$.

insert $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


Binary Search Tree II

Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I.

insert $k$: Insert a node containing $k$ as key into $T$.

find $k$: Report whether $T$ has a node containing $k$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

10
insert 30
insert 88
insert 12
insert 1
insert 20
find 12
insert 17
insert 25
find 16
print

Sample Output 1

yes
no
1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


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

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

struct Node *root,*NIL;

void inorder(struct Node *);
void preorder(struct Node *);
struct Node *find(struct Node *,int );
void insert(int );

int main(){
  int i,n,x;
  char retu[10];
  struct Node *ori;

  scanf("%d",&n);
  for(i=0;i<n;i++){
    scanf("%s",retu);
    if(strcmp(retu,"insert")==0){
      scanf("%d",&x);
      insert(x);
    }
    else if(strcmp(retu,"print")==0){
      inorder(root);
      printf("\n");
      preorder(root);
      printf("\n");
    }
    else{
      scanf("%d",&x);
      ori=find(root,x);
      if(ori!=NIL)
	printf("yes\n");
      else printf("no\n");
    }
  }
  return 0;
}

void inorder(struct Node *u){
  if(u==NIL) return;
  inorder(u->left);
  printf(" %d",u->key);
  inorder(u->right);
}

void preorder(struct Node *u){
  if(u==NIL) return;
  printf(" %d",u->key);
  preorder(u->left);
  preorder(u->right);
}

struct Node *find(struct Node *u,int k){

  while(u!=NIL && k!= u->key){
    if(k < u->key) u=u->left;
    else u=u->right;
  }
  return u;
}

void insert(int k){

  struct Node *y=NIL;
  struct Node *x=root;
  struct Node *z;

  z=(struct Node *)malloc(sizeof(struct Node));
  z->key=k;
  z->right=NIL;
  z->left=NIL;

  while(x!=NIL){
    y=x;
    if(z->key < x->key){
      x=x->left;
    }
    else x=x->right;
  }

  z->parent=y;
  if(y==NIL) root=z;
  else{
    if(z->key < y->key) y->left=z;
    else y->right=z;
  }
}


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

typedef struct P{
    int num;
    int left;
    int right;
}Node;

void pre(Node node[],int n){
    if(n==-1){return;}
    printf(" %d",node[n].num);
    pre(node,node[n].left);
    pre(node,node[n].right);
}

void ino(Node node[],int n){
    if(n==-1){return;}
    ino(node,node[n].left);
    printf(" %d",node[n].num);
    ino(node,node[n].right);
}

int insert(Node node[],int n,int x,int num){
    int ii=0;
    if(n==-1||node[n].num==-1){
        node[x].num = num;
        return x;
    }else if(node[n].num>num){
        ii = insert(node,node[n].left,x,num);
        if(ii!=0){
            node[n].left = ii;
        }
    }else{
        ii = insert(node,node[n].right,x,num);
        if(ii!=0){
            node[n].right = ii;
        }
    }
    return 0;
}

int find(Node node[],int n,int num){
    if(n==-1){return 0;}
    else if(node[n].num>num){return find(node,node[n].left,num);}
    else if(node[n].num<num){return find(node,node[n].right,num);}
    else{return 1;}
}

int main(void){
    int n,i,j,x,y;
    char str[7];
    Node *node;
    scanf("%d",&n);
    node = (Node*)malloc(sizeof(Node)*n);
    for(i=0;i<n;i++){
        node[i].num = -1;
        node[i].left = -1;
        node[i].right = -1;
    }
    x = 0;
    for(i=0;i<n;i++){
        scanf("%s",str);
        if(str[0]=='i'){
            scanf("%d",&y);
            insert(node,0,x,y);
            x++;
        }else if(str[0]=='f'){
            scanf("%d",&y);
            y = find(node,0,y);
            if(y==1){printf("yes\n");}
            else{printf("no\n");}
        }else{
            ino(node,0);
            printf("\n");
            pre(node,0);
            printf("\n");
        }
    }
    return 0;
}


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

struct node{
  struct node *right;
  struct node *left;
  struct node *parent;
  int key;
};
typedef struct node * Node;
#define NIL NULL

Node root;

Node treeMinimum(Node x){
  while( x->left != NIL){
    x = x->left;
  }
  return x;
}

Node treeSearch(Node u, int k){
  if( u == NIL || k == u->key){
    return u;
  }
  if(k < u->key){
    return treeSearch(u->left,k);
  }
  else
    return treeSearch(u->right,k);

  while(u != NIL && k != u->key){
    if(k < u->key){
      u = u->left;
    }
    else if(k > u->key){
      u = u->right;
    }
  }
  return u;

}

Node treeSuccessor(Node x){
  Node y;
  if(x->right != NIL){
    return treeMinimum(x->right);
  }
  y = x->parent;
  while(y != NIL && x == y->right){
    x = y;
    y = y->parent;
  }
  return y;
}

void treeDelete(Node z){
  Node y; // node to be deleted
  Node x; // child of y

  if(z->left == NIL || z->right == NIL){
    y = z;
  }
  else
    y = treeSuccessor(z);

  if(y->left != NIL){
    x = y->left;
  }
  else
    x = y->right;

  if(x != NIL){
    x->parent = y->parent;
  }

  if (y->parent == NIL){
      root = x;
  }
  else if( y == y->parent->left){
    y->parent->left = x;
  }
   else
     y->parent->right = x;
  if (y != z){
     z->key = y->key;
  }

}

void insert(int k){
  Node y = NIL;
  Node x = root;
  Node z;

  z = malloc(sizeof(struct node));
  z->key = k;
  z->left = NIL;
  z->right = NIL;

  while(x != NIL){
    y = x;
     if(z->key <  x->key){
       x = x->left;
     }
     else
       x = x->right;
  }
   z->parent = y;
   if(y == NIL){
     root = z;
   }
   else if(z->key <  y->key){
     y->left = z;
   }
   else
     y->right = z;

  }

void inorder(Node u){
if(u != NIL){
    inorder(u->left);
    printf(" %d",u->key);
    inorder(u->right);
 }
}

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

int main(){
  int n, i, x;
  char com[20];
  scanf("%d", &n);

  for ( i = 0; i < n; i++ ){
    scanf("%s", com);
    if ( com[0] == 'f' ){
      scanf("%d", &x);
      Node t = treeSearch(root, x);
      if ( t != NIL ) printf("yes\n");
      else printf("no\n");
    }
    if ( com[0] == 'i' ){
      scanf("%d", &x);
      insert(x);
    }
    else if ( com[0] == 'p' ){
      inorder(root);
      printf("\n");
      preorder(root);
      printf("\n");
    } else if ( com[0] == 'd' ){
	scanf("%d", &x);
	treeDelete(treeSearch(root, x));
	}
  }

  return 0;
}

Binary Search Tree III

Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II.

insert $k$: Insert a node containing $k$ as key into $T$.

find $k$: Report whether $T$ has a node containing $k$.

delete $k$: Delete a node containing $k$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases:

If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$).

If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent.

If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print

Sample Output 1

yes
yes
yes
no
no
no
yes
yes
1 2 3 7 8 22
8 2 1 3 7 22
1 2 8 22
8 2 1 22

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


#include<stdio.h>
#define M 2000000000

int n,a[M+1];

void maxHeapify(int i){
  int l,r,largest,S;

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

  if(l<=n && a[l]>a[i]) largest=1;
  else largest=i;
  if(l<=n && a[r]>a[largest]) largest=r;

  if(largest!=i){
    S = a[i];
    a[i] = a[largest];
    a[largest] = S;
    maxHeapify(largest);
  }
}

int main(){
  int i;

  scanf("%d",&n);

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

  for(i=n/2;i>=1;i--){
    maxHeapify(i);
  }

  for(i=1;i<=n;i++){
    printf(" %d",a[i]);
  }

  printf("\n");

  return 0;
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Maximum Heap

A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.

Here is an example of a max-heap.

Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.

$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.

1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i　// value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively

The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.

1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)

Input

In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).

Output

Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.

Constraint

$1 \leq H \leq 500,000$

$-2,000,000,000 \leq$ value of a node $\leq 2,000,000,000$

Sample Input 1

10
4 1 3 2 16 9 10 14 8 7

Sample Output 1

16 14 10 8 7 9 3 2 4 1

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


#include <stdio.h>

int A[500000];
int h; /* ヒープサイズ */

void maxHeapify(int*, int);
void buildMaxHeap(int*);

int main()
{
  int i,key;

  scanf("%d",&h); /* ヒープのサイズ */

  /* 初期化 */
  for(i = 0;i < h+1;i++){
    A[i] = -2000000001;
  }

  /* とりあえず、配列Aに値を入れる */
  for(i = 1;i < h+1; i++){
    scanf("%d",&key);
    A[i] = key;
  }

  buildMaxHeap(A);

  /* 出力 */
  for(i = 1;i < h+1;i++){
    printf(" %d",A[i]);
  }
  printf("\n");
  return 0;
}

void maxHeapify(int *A,int i)
{
  int l,r,largest,tmp;

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

  /* 左の子、自分、右の子で値が最大のノードを選ぶ */
  if(l <= h && A[l] > A[i]) largest = l; /* 左の子が自分より大きい場合 */
  else largest = i; /* 自分が左の子より大きい場合 */

  if(r <= h && A[r] > A[largest]) largest = r; /* 右の子がlargestより大きい場合 */

  if(largest != i){ // iの子の方が値が大きい場合
    tmp = A[i];     // A[i]とA[largest]を交換
    A[i] = A[largest];
    A[largest] = tmp;
    maxHeapify(A,largest); //再帰的に呼び出し
  }
}

void buildMaxHeap(int *A)
{
  int i;
  for(i = h/2 ;i >= 1; i--){
    maxHeapify(A,i);
  }
}


#include<stdio.h>
#define MAX 2000000

int H,A[MAX+1];

int parent(int i) { return i/2; }
int left(int i) { return i*2; }
int right(int i) { return i*2+1; }
void maxHeapify(int);
void buildMaxHeap();

int main()
{
  int i;

  scanf("%d",&H);
  for(i=1;i<=H;i++){
    scanf("%d",&A[i]);
  }

  buildMaxHeap();

   for(i=1;i<=H;i++){
    printf(" %d",A[i]);
  }
   printf("\n");

  return 0;
}

void maxHeapify(int i)
{
  int largest;
  int l = left(i);
  int r = right(i);
  int x;
  //自分、左の子、右の子の中から値が最大ノードを選ぶ
  if( l <= H && A[l] > A[i] ) largest = l;
  else largest = i;
  if( r <= H && A[r] > A[largest] ) largest = r;

  if(largest != i){ //iの子の方が値が大きい場合
    //printf("yes\n");
    x = A[i];
    A[i] = A[largest];
    A[largest] = x;
    maxHeapify(largest); //再帰的に呼び出し
  }
}

void buildMaxHeap()
{
  int i;
  for(i=H/2;i>=1;i--){
    maxHeapify(i);
  }
}


#include <stdio.h>
#include <string.h>
#define MAX_HEAP 1500000
#define NEG_INF -100000

int heap_size = 1;
int parent(int);
int left(int);
int right(int);

void maxHeapfy(int *, int);
void maxHeapInsert(int *, int);
void heapIncreaseKey(int *, int, int);
int heapExtractMax(int *);

int main(void) {
  int key;
  int ary[MAX_HEAP];
  char order[10];

  while (1) {
    scanf("%s %d", order, &key);
    if (order[0] == 'i') {
      maxHeapInsert(ary, key);
    } else if (order[1] == 'x') {
      int max = heapExtractMax(ary);
      printf("%d\n", max);
    } else {
      break;
    }
  }

  return 0;
}

int parent(int i) {
  return i/2;
}
int left(int i) {
  return 2*i;
}
int right(int i) {
  return 2*i + 1;
}

void maxHeapify(int *A, int i) {
  int l = left(i);
  int r = right(i);
  int largest;

  if (l <= heap_size && A[l] > A[i]) {
    largest = l;
  } else {
    largest = i;
  }
  if (r <= heap_size && A[r] > A[largest]) {
    largest = r;
  }

  if (largest != i) {
    /* A[i]とA[largest]の値を交換 */
    int tmp = A[largest];
    A[largest] = A[i];
    A[i] = tmp;

    maxHeapify(A, largest);
  }
}

void maxHeapInsert(int *A, int key) {
  heap_size++;
  A[heap_size] = NEG_INF;
  heapIncreaseKey(A, heap_size, key);
}

void heapIncreaseKey(int *A, int i, int key) {
  if (key < A[i]) {             /* 新しいキーは現在のキーより小さい */
    return;
  }

  A[i] = key;
  while (i > 1 && A[parent(i)] < A[i]) {
    /* 親と子を入れ替える */
    int tmp = A[i];
    A[i] = A[parent(i)];
    A[parent(i)] = tmp;
    i = parent(i);
  }
}

int heapExtractMax(int *A) {
  if (heap_size < 1) {          /* ヒープアンダーフロー */
    return -1;
  }

  int max = A[1];
  A[1] = A[heap_size];
  heap_size--;
  maxHeapify(A, 1);
  return max;
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Priority Queue

A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations:

$insert(S, k)$: insert an element $k$ into the set $S$

$extractMax(S)$: remove and return the element of $S$ with the largest key

Write a program which performs the $insert(S, k)$ and $extractMax(S)$ operations to a priority queue $S$.
The priority queue manages a set of integers, which are also keys for the priority.

Input

Multiple operations to the priority queue $S$ are given. Each operation is given by "insert $k$", "extract" or "end" in a line. Here, $k$ represents an integer element to be inserted to the priority queue.

The input ends with "end" operation.

Output

For each "extract" operation, print the element extracted from the priority queue $S$ in a line.

Constraints

The number of operations $\leq 2,000,000$

$0 \leq k \leq 2,000,000,000$

Sample Input 1

insert 8
insert 2
extract
insert 10
extract
insert 11
extract
extract
end

Sample Output 1

8
10
11
2


#include <stdio.h>
#define N 2000000
#define INF 100000000

//operation of pushing or popping
void maxHeapInsert( int A[], int key );
void heapIncreaseKey( int A[], int, int key );
int  heapExtractMax( int A[] );

//make a max heap
void swap( int*, int* );
void maxHeapify( int A[], int i );
void buildMaxHeap( int A[] );

//declare sevaral global variables
int n = 0;

int main(){
    int A[N+1], i, j, data;
    char com[10];

    //input and some procedures
    while( 1 ){
	scanf("%s", com);
	if( com[0] == 'i' ){
	    scanf("%d", &data);
	    maxHeapInsert(A, data);
	}
	else if( com[0] == 'e' && com[1] == 'x' ){
	    data = heapExtractMax(A);
	    printf("%d\n", data);
	}
	else break;//when end command was inputted
    }
    return 0;
}

//----------------------------------------------------------------
inline void swap( int* a, int *b ){
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
    return;
}
void maxHeapify( int A[], int p ){
    int l, r, largest;

    //initialize
    l = 2*p;
    r = 2*p + 1;
    //compare those values of p , l and r
    largest = p;
    if( A[l] > A[p] && l <= n ) largest = l;
    if( A[r] > A[largest] && r <= n ) largest = r;
    //swap those values
    if( largest != p ){
	swap( &A[largest], &A[p] );
	maxHeapify( A, largest );
    }
    return ;
}
void buildMaxHeap( int A[] ){
    int l, p, r, i, heap_size = N;

    for( i=N/2; i>=1; i-- ) maxHeapify( A, i );

    return ;
}

//------------------------------------------------------------------
void maxHeapInsert( int A[], int key ){

    n += 1;
    A[n] = -INF;
    heapIncreaseKey( A, n, key );

    return ;
}

void heapIncreaseKey( int A[], int i, int key ){
    int p = i/2;

    A[i] = key;
    while( i>1 && A[i] > A[p] ){
	swap( &A[i], &A[p] );
	i = p;
	p = p/2;
    }
    return ;
}

//------------------------------------------------------------------
int heapExtractMax( int A[] ){
    int max, heap_size = n;

    max = A[1];
    A[1] = A[heap_size];
    n--;
    maxHeapify( A, 1 );

    return max;
}


#include<stdio.h>
#define MAX 2000000

int size, A[MAX+1];

void maxHeapify(int i){
  int l, r, largest, t;
  l = 2*i;
  r = 2*i+1;
  if ( l <= size && A[l] > A[i] ) largest = l;
  else largest = i;
  if ( r <= size && A[r] > A[largest] ) largest = r;
  if ( largest != i ){
    t = A[i]; A[i] = A[largest]; A[largest] = t;
    maxHeapify(largest);
  }
}

int extract(){
  int maxv;
  if ( size < 1 ) return;
  maxv = A[1];
  A[1] = A[size--];
  maxHeapify(1);
  return maxv;
}

void increaseKey(int i, int key){
  int temp;
  if ( key < A[i] ) return;
  A[i] = key;
  while ( i > 1 && A[i/2] < A[i] ){
    temp = A[i];
    A[i] = A[i/2];
    A[i/2] = temp;
    i = i/2;
  }
}

void insert(int key){
  size++;
  A[size] = -1000000001;
  increaseKey(size, key);
}

main(){
  int key;
  char com[10];
  while(1){
    scanf("%s", com);
    if ( com[0] == 'i' ){
      scanf("%d", &key);
      insert(key);
    } else if ( strcmp(com, "extract") == 0  ){
      printf("%d\n", extract());
    } else break;
  }

  return 0;
}


#include<stdio.h>

main(void){
    int x;
    int i = 1;
    while(scanf("%d", &x)){
       printf("Case %d: %d\n", i, x);
       i++;
    }
}

Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Constraints

1 ≤ x ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19


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

int main(void) {
	int i,a,b;
	char op;

	for(i=1; ;i++){
		scanf("%d%c%d",&a,&op,&b);
		if(op=='?') break;
		if(op=='+'){
			printf("%d\n",a+b);
		}
		if(op=='-'){
			printf("%d\n",a-b);
		}
		if(op=='*'){
			printf("%d\n",a*b);
		}
		if(op=='/'){
			printf("%d\n",a/b);
		}
	}
	return 0;
}

Simple Calculator

Write a program which reads two integers a, b and an operator op, and then prints the value of a op b.

The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part.

Input

The input consists of multiple datasets. Each dataset is given in the following format.

a op b

The input ends with a dataset where op = '?'. Your program should not process for this dataset.

Output

For each dataset, print the value in a line.

Constraints

0 ≤ a, b ≤ 20000

No divisions by zero are given.

Sample Input 1

1 + 2
56 - 18
13 * 2
100 / 10
27 + 81
0 ? 0

Sample Output 1

3
38
26
10
108


#include <stdio.h>

int main(){
for( ; ; ){

 int a, b, i;
 char op;

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

 switch( op ){

 case '+' : printf("%d\n", a + b);break;
 case '-' : printf("%d\n", a - b);break;
 case '*' : printf("%d\n", a * b);break;
 case '/' : printf("%d\n", a / b);break;
 case '?' : return 0;break;
}}
 return 0;
}


#include <stdio.h>
int main(void){
    int a,op,b;

    while(1){
    scanf("%d %c %d",&a, &op, &b);

    if ( op == '+' )printf("%d\n",a + b );
    else if ( op == '-' )printf("%d\n",a - b );
    else if ( op == '*' )printf("%d\n",a * b );
    else if ( op == '/' )printf("%d\n",a / b );

    else ( op == '?'); printf(" ");
    }

    return 0;

}


#include <stdio.h>
int main(void)
{
int n;
int i = 1;

scanf("%d",&n);

while( i <= n){

while(1 <= n){
if(i % 3 == 0)
   break;
else if((i / 10) % 10 == 3)
   break;
else if(i / 10){
   if(i % 10 == 3)
   break;
}
else
i++;
}
printf("%d",i);
i++;
}
return 0;
}

Structured Programming

In programming languages like C/C++, a goto statement provides an unconditional jump from the "goto" to a labeled statement. For example, a statement "goto CHECK_NUM;" is executed, control of the program jumps to CHECK_NUM. Using these constructs, you can implement, for example, loops.

Note that use of goto statement is highly discouraged, because it is difficult to trace the control flow of a program which includes goto.

Write a program which does precisely the same thing as the following program (this example is wrtten in C++). Let's try to write the program without goto statements.

void call(int n){
int i = 1;
CHECK_NUM:
int x = i;
if ( x % 3 == 0 ){
cout << " " << i;
goto END_CHECK_NUM;
}
INCLUDE3:
if ( x % 10 == 3 ){
cout << " " << i;
goto END_CHECK_NUM;
}
x /= 10;
if ( x ) goto INCLUDE3;
END_CHECK_NUM:
if ( ++i <= n ) goto CHECK_NUM;

cout << endl;
}

Input

An integer n is given in a line.

Output

Print the output result of the above program for given integer n.

Constraints

3 ≤ n ≤ 10000

Sample Input

30

Sample Output

3 6 9 12 13 15 18 21 23 24 27 30

Put a single space character before each element.


How many ways?

Write a program which identifies the number of combinations of three integers which satisfy the following conditions:

You should select three distinct integers from 1 to n.

A total sum of the three integers is x.

For example, there are two combinations for n = 5 and x = 9.

1 + 3 + 5 = 9

2 + 3 + 4 = 9

Input

The input consists of multiple datasets. For each dataset, two integers n and x are given in a line.

The input ends with two zeros for n and x respectively. Your program should not process for these terminal symbols.

Constraints

3 ≤ n ≤ 100

0 ≤ x ≤ 300

Output

For each dataset, print the number of combinations in a line.

Sample Input

5 9
0 0

Sample Output

2

Note

      解説


#include <stdio.h>
#include <ctype.h>

int main(void){
	char ch[1001];
	int i;
	int sum;
	while(1){
		scanf("%s",ch);
		i = 0;
		sum = 0;
	while(ch[i] != '\n'){
		sum += (ch[i] - '0');
		i++;
	}
	printf("%d\n",sum);
	}
	return 0;
}

Sum of Numbers

Write a program which reads an integer and prints sum of its digits.

Input

The input consists of multiple datasets. For each dataset, an integer x is given in a line. The number of digits in x does not exceed 1000.

The input ends with a line including single zero. Your program should not process for this terminal symbol.

Output

For each dataset, print the sum of digits in x.

Sample Input

123
55
1000
0

Sample Output

6
10
1


#include <stdio.h>

int next_permutation(int *A, int size)
{
    if (size == 1) return 0;

    int i, flag = 0;
    for (i = size - 2; i >= 0; i--) {
        if (A[i] < A[i+1]) {
            flag = 1;
            break;
        }
    }

    if (flag == 0) return 0;

    int j, tmp;
    for (j = size - 1; j > i; j--) {
        if (A[j] > A[i]) {
            tmp = A[j];
            A[j] = A[i];
            A[i] = tmp;
            break;
        }
    }
    int mid = (size - i - 1) / 2;
    for (j = 1; j <= mid; j++) {
        tmp = A[i+j];
        A[i+j] = A[size-j];
        A[size-j] = tmp;
    }
    return 1;
}

void print_array(int *A, int size)
{
    int i;
    printf("%d", A[0]);
    for (i = 1; i < size; i++) printf(" %d", A[i]);
    putchar('\n');
}

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

    int A[9];
    int i;
    for (i = 0; i < n; i++) A[i] = i + 1;

    do {
        print_array(A, n);
    } while (next_permutation(A, n));

    return 0;
}

Permutation Enumeration

For given an integer $n$, print all permutations of $\{1, 2, ..., n\}$ in lexicographic order.

Input

An integer $n$ is given in a line.

Output

Print each permutation in a line in order. Separate adjacency elements by a space character.

Constraints

$1 \leq n \leq 9$

Sample Input 1

2

Sample Output 1

1 2
2 1

Sample Input 2

3

Sample Output 2

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1


#include <stdio.h>

int main(void) {
	int n, i, j;
	scanf("%d", &n);
	printf("%d:", n);

	for(i=2; i<=n; i++){
		while(n%i == 0){
			printf(" %d", i);
			n = n / i;
		}
	}
	putchar('\n');
	return 0;
}

Prime Factorization

Factorize a given integer n.

Input

n

An integer n is given in a line.

Output

Print the given integer n and :. Then, print prime factors in ascending order. If n is divisible by a prime factor several times, the prime factor should be printed according to the number of times. Print a space before each prime factor.

Constraints

2 ≤ n ≤ 109

Sample Input 1

12

Sample Output 1

12: 2 2 3

Sample Input 2

126

Sample Output 2

126: 2 3 3 7


#include <stdio.h>
int main(void){
    long long int A,B,C,D;
    scanf("%d",&A);
    scanf("%d",&B);
    scanf("%d",&C);
    scanf("%d",&D);
    if ((A>D)||(B<C))
        printf("No");
    else
        printf("Yes");
}

Score : 100 points

Problem Statement

You are given an integer K.
Print the string obtained by repeating the string ACL K times and concatenating them.

For example, if K = 3, print ACLACLACL.

Constraints

1 \leq K \leq 5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the string obtained by repeating the string ACL K times and concatenating them.

Sample Input 1

3

Sample Output 1

ACLACLACL


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

int main(void){

  int len,i;
  char c[1001];
  if(scanf("%s",c)==1){
    len = strlen(c);
    if(c[len-1] == 's'){
      c[len-1] = 'e';
      c[len] = 's';
      c[len+1] = '\0';
    }
    else{
      c[len] = 's';
      c[len+1] = '\0';
    }
    for(i=0;i<=len;i++) printf("%c",c[i]);
  }

  return 0;
}

Score : 100 points

Problem Statement

In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.

In Taknese, the plural form of a noun is spelled based on the following rules:

If a noun's singular form does not end with s, append s to the end of the singular form.

If a noun's singular form ends with s, append es to the end of the singular form.

You are given the singular form S of a Taknese noun. Output its plural form.

Constraints

S is a string of length 1 between 1000, inclusive.

S contains only lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the plural form of the given Taknese word.

Sample Input 1

apple

Sample Output 1

apples

apple ends with e, so its plural form is apples.

Sample Input 2

bus

Sample Output 2

buses

bus ends with s, so its plural form is buses.

Sample Input 3

box

Sample Output 3

boxs


#include<stdio.h>
#include <string.h>
int main(void)
{
  int D1[100],D2[100],i=0,N,cnt=0,ans=0;

  scanf("%d",&N);
  for(i;i<N;i++)
  {
    scanf("%d %d",&D1[i],&D2[i]);
    if(D1[i]==D2[i]){
      cnt++;
      if(cnt>=3){ans=1;}
    }else{
      cnt=0;
    }
  }

  if(ans==1){
    printf("Yes");
  }else{
    printf("No");
  }

  return 0;
}

Score : 200 points

Problem Statement

Tak performed the following action N times: rolling two dice.
The result of the i-th roll is D_{i,1} and D_{i,2}.

Check if doublets occurred at least three times in a row.
Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.

Constraints

3 \leq N \leq 100

1\leq D_{i,j} \leq 6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
D_{1,1} D_{1,2}
\vdots
D_{N,1} D_{N,2}

Output

Print Yes if doublets occurred at least three times in a row. Print No otherwise.

Sample Input 1

5
1 2
6 6
4 4
3 3
3 2

Sample Output 1

Yes

From the second roll to the fourth roll, three doublets occurred in a row.

Sample Input 2

5
1 1
2 2
3 4
5 5
6 6

Sample Output 2

No

Sample Input 3

6
1 1
2 2
3 3
4 4
5 5
6 6

Sample Output 3

Yes


Score : 400 points

Problem Statement

There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.

Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.

You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K].
Let S be the union of these K segments.
Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.

When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.

To help Tak, find the number of ways to go to Cell N, modulo 998244353.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq K \leq \min(N, 10)

1 \leq L_i \leq R_i \leq N

[L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
L_1 R_1
L_2 R_2
:
L_K R_K

Output

Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.

Sample Input 1

5 2
1 1
3 4

Sample Output 1

4

The set S is the union of the segment [1, 1] and the segment [3, 4], therefore S = \{ 1, 3, 4 \} holds.

There are 4 possible ways to get to Cell 5:

1 \to 2 \to 3 \to 4 \to 5,

1 \to 2 \to 5,

1 \to 4 \to 5 and

1 \to 5.

Sample Input 2

5 2
3 3
5 5

Sample Output 2

0

Because S = \{ 3, 5 \} holds, you cannot reach to Cell 5.
Print 0.

Sample Input 3

5 1
1 2

Sample Output 3

5

Sample Input 4

60 3
5 8
1 3
10 15

Sample Output 4

221823067

Note that you have to print the answer modulo 998244353.


#include <stdio.h>

int main(void) {

    int x;

    scanf("%d", &x);

    if (x == 1)
        printf("0\n");

    else
        printf("1\n");

    return 0;
}

Score : 100 points

Problem Statement

Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.

Constraints

0 \leq x \leq 1

x is an integer

Input

Input is given from Standard Input in the following format:

x

Output

Print 1 if x is equal to 0, or 0 if x is equal to 1.

Sample Input 1

1

Sample Output 1

0

Sample Input 2

0

Sample Output 2

1


#include<stdio.h>

int main(){
int x;
  scanf("%d",&x);
  if(x==0)printf("1\n");
  else printf("0\n");
  return 0;
}


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

int main() {
    int x;
    scanf("%d", &x);
    if(x == 1){
        printf("0\n");
    }else{
        printf("1");
    }

    return 0;
}


#include <stdio.h>
int main()
{
  int c;

  scanf("%c", c);
  if (c == '0')
    printf("1");
  else
    printf("0");
  return 0;
}


#include <stdio.h>
int main(void){

    int a,b,c,d,max;

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

    int i,j;
    if(a<0 && c<0){
        max=a*c;
        printf("%d",max);
    }
    if(a>0 || c>0){
        max=-10000;
    for(i=a;i<=b;i++){
        for(j=c;j<=d;j++){
        if(max<i*j){
            max=i*j;
        }
        printf("%d",max);
        }
    }
    }

    return 0;
}

Score : 200 points

Problem Statement

Given are integers a,b,c and d.
If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?

Constraints

-10^9 \leq a \leq b \leq 10^9

-10^9 \leq c \leq d \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

Print the answer.

Sample Input 1

1 2 1 1

Sample Output 1

2

If x = 1 and y = 1 then x \times y = 1.
If x = 2 and y = 1 then x \times y = 2.
Therefore, the answer is 2.

Sample Input 2

3 5 -4 -2

Sample Output 2

-6

The answer can be negative.

Sample Input 3

-1000000000 0 -1000000000 0

Sample Output 3

1000000000000000000


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

int main(void){
    unsigned int N;
    unsigned long a=1,b=1,c=1,mod=((long)(pow(10.0,9.0))+7);
    scanf("%u",&N);
    for(int i=0;i<N;i++){

        a=a*2%mod+((a*2%mod)*2%mod)*2%mod;
        b=(((b*2%mod)*2%mod)*2%mod+b)%mod;
        c=((c*2%mod)*2%mod)*2%mod;
    }

    unsigned long ans=(a-b*2%mod+c)%mod;
    if(N==1)ans=0;

    ans=(ans+mod)%mod;
    printf("%lu",ans);

    return 0;
}

Score : 300 points

Problem Statement

How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?

0 \leq A_i \leq 9

There exists some i such that A_i=0 holds.

There exists some i such that A_i=9 holds.

The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^9 + 7.

Sample Input 1

2

Sample Output 1

2

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

Sample Input 2

1

Sample Output 2

0

Sample Input 3

869121

Sample Output 3

2511445


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

typedef long long ll;
#define IMF 1000000007

int main(void){
  ll n;
  scanf("%lld",&n);

  ll ans = 0;
  ll dai = 1 , syou = 1 , tyu = 1;
  int count = 0 , kake , tas;
  if(n == 1){
    ans = 0;
  }

  else{
    int count = 0;
    while(count < n){
      dai *= 10;
      dai %= IMF;
      syou *= 8;
      syou %= IMF;
      tyu *= 9;
      tyu %= IMF;
      count ++;
    }
    if(dai <= tyu*2 - syou){
      ans = (IMF+dai) - (tyu * 2 - syou);
    }
    else{
      ans = dai - (tyu * 2 - syou);
    }
  }

  printf("%lld\n",ans);

  return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <inttypes.h>

//int compare_int(const void *a, const void *b){//qsort 整数比較<
//	return *(int*)a - *(int*)b;
//}
//int compare_int2(const void *a, const void *b){//qsort 整数比較>
//	return *(int*)b - *(int*)a;
//}
//

//long long int combination(int n, int r)
//{
//	if (r == 0 || r == n)
//		return (1);
//	else if (r == 1)
//		return (n);
//	return (combination(n - 1, r - 1) + combination(n - 1, r));
//}

int main(void){
	int n;
	long long int nine=0,eigth=0,ten=0,ans=0;
	int i;

	scanf("%d",&n);
	if(n<2){
		printf("0");
		return 0;
	}else if(n==2){
		printf("2");
		return 0;
	}
	for(i=0;i<n;i++){
		if(i==0){
			nine=9;
			eigth=8;
			ten=10;
		}
		else{
			nine=nine*9%1000000007;
			eigth=eigth*8%1000000007;
			ten=ten*10%1000000007;
		}
	}
	ans=(ten+eigth-nine*2)%1000000007;
	if(ans<0){
		ans=1000000007+ans;
	}
	printf("%lld",ans);

	return 0;
}


#include <stdio.h>

int main(void){
int D,T,S;
scanf("%d",&D);
scanf("%d",&T);
scanf("%d",&S);
if(D/S < T )printf("Yes\n");
else printf("No\n");
return 0;

}

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes 20 minutes to go 2000 meters to the place at a speed of 100 meters per minute. They have planned to meet in 20 minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


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

int t[300000];
int c[300000];

int root(int x){
  if(t[x]==x) return x;
  return t[x]=root(t[x]);
}

int main(){
  int N,M;
  scanf("%d %d",&N,&M);
  for(int i=1;i<=N;i++){
    t[i]=i;
    c[i]=1;
  }
  int A,B,RA,RB;
  for(int i=1;i<=M;i++){
    scanf("%d %d",&A,&B);
    if(A>B){
      A^=B;
      B^=A;
      A^=B;
    }
    RA=root(A);
    RB=root(B);
    if(RA!=RB){
      t[B]=A;
      c[A]+=c[B];
    }
  }
  int Ans=0;
  for(int i=1;i<=N;i++){
    if(root(i)==i)
      if(Ans<c[i])
        Ans=c[i];
  }
  printf("%d\n",Ans);
  return 0;
}

Score : 400 points

Problem Statement

There are N persons called Person 1 through Person N.

You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.

If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.

Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.

At least how many groups does he need to make?

Constraints

2 \leq N \leq 2\times 10^5

0 \leq M \leq 2\times 10^5

1\leq A_i,B_i\leq N

A_i \neq B_i

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
\vdots
A_M B_M

Output

Print the answer.

Sample Input 1

5 3
1 2
3 4
5 1

Sample Output 1

3

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

Sample Input 2

4 10
1 2
2 1
1 2
2 1
1 2
1 3
1 4
2 3
2 4
3 4

Sample Output 2

4

Sample Input 3

10 4
3 1
4 1
5 9
2 6

Sample Output 3

3


#include<stdio.h>
int main(){
  int n,x,t,answer=0,i,counter=0;
  scanf("%d %d %d",&n,&x,&t);
  while(n-x>=0){
      n=n-x;
      counter=counter+1;
    }
  if(n>0){
    counter=counter+1;
  }
  answer=t*counter;
  printf("%d",answer);
  return 0;
}

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


#include <stdio.h>
int main(void){
    int a,b,c,d;

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

        if(a < b){
            printf("%d\n",c);

// 剰余の処理
        }else{
            if (a % b == 0) {
                d = a / b;
            }else{
                d = a / b + 1;
            }

            printf("%d\n",c * d);
            }

    return 0;
}


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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define MAXSIZE 10001
int main(int argc, char *argv[]) {
//	char res[4];
	char N[MAXSIZE];
	scanf("%s", N);
	int sizeN = strlen(N);

	if (N[0] - '0' == 0)
	{
		printf("%s", "YES");
		return;
	}
	int i = 0;
	int sum = 0;
	for (i = 0; i < sizeN; i++)
	{
		sum = sum + (N[i] - '0');
	}

	if (sum % 9 == 0)
	{
		printf("%s", "YES");

		return ;
	}
	else
	{
		printf("%s", "NO");
	}

	return 0;
}

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
//if(strcmp(s[i],"AC")==0)
//if(s[l]=='#')
/*小文字判定
if((moji>= 'a') && (moji<='z')){
    printf("a\n");
    return 0;
  }
  */
//文字列中の一文字⇒数字の時は s[i]-'0'
int W_Length(char *str){
	int length = 0;
	while(*str++ != '\0')
		length++;
	return length;
}

void swap(long long int *a, long long int *b){
  int temp;
  temp=*a;
  *a=*b;
  *b=temp;
}
//swap(&a, &b)

double deg(double theta){//deg to theta
return theta*(2*3.14159265359)/360;
}

long long int cmp( const void *p, const void *q ) {
    return *(long long int*)p - *(long long int*)q;
}//ちいさい順
//qsort(a,n,sizeof(long long int),cmp);

int cmp_s(const void * left, const void * right)
{
	char *left_char = (char *)left;
  char *right_char = (char *)right;
  return strcmp(left_char, right_char);
}
//qsort(s,n,sizeof(s[0]),cmp_s);
//char s[n][11]

long long int GCD(long long int a, long long int b){
  long long int L=a,S=b;
  while(1){
    if(S>L){
      L=S+L;
      S=L-S;
      L=L-S;
    }
    if(L%S==0){
      return S;
    }
    L=L%S;
  }

}

long long int LCM(long long int a, long long int b){
  return a*b/(GCD(a,b));
}

int main (void)
{
	long long int n,i,min,k,a[210000],max,j=1,count=0;
scanf("%lld",&n);
  scanf("%lld",&a[0]);
  max=a[0];
for(i=1;i<n;i++){
  scanf("%lld",&a[i]);
  if(a[i]>max){
    max=a[i];
    continue;
  }
  count+=max-a[i];
  continue;
}

  printf("%lld",count);
return 0;
}

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

1 \leq N \leq 2\times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


#include <stdio.h>

int main(void)
{
        int n,i,s,c=0;
        scanf("%d",&n);
        int a[n];
        for(i=0;i<n;i++)
                scanf("%d",&a[i]);

        for(i=1;i<n;i++){
                if(a[i]<a[i-1]){
                        s=a[i-1]-a[i];
                        c+=n;
                        a[i]+=n;
                }
        }
        printf("%d\n",c);
        return 0;
}