#include <stdio.h>
#include <stdlib.h>
#define N 10000
#define INF 200000
#define WHITE 0
#define GRAY 1
#define BLACK 2

int G[N][N], n;

void dijkstra(void) {
  int *d, *color;
  int i, u, mincost;

  d = (int*)malloc(sizeof(int) * n);
  color = (int*)malloc(sizeof(int) * n);
  for(i = 0; i < n; i++) {
    d[i] = INF;
    color[i] = WHITE;
  }
  d[0] = 0;

  while(1){
    mincost = INF;
    for(i = 0; i < n; i++) {
      if(color[i] != BLACK && d[i] < mincost){
        mincost = d[i];
        u = i;
      }
    }
    if(mincost == INF) break;
    color[u] = BLACK;
    for(i = 0; i < n; i++) {
      if(color[i] != BLACK && G[u][i] != INF && d[u] + G[u][i] < d[i]) {
        d[i] = d[u] + G[u][i];
      }
    }
  }
  for(i = 0; i < n; i++) {
    printf("%d %d\n", i, d[i]);
  }
}

int main(){
  int i, j, u, v, k, c;

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

  for(i = 0; i < n; i++) {
    scanf("%d", &u);
    scanf("%d", &k);
    for(j = 0; j < k; j++) {
      scanf("%d", &v);
      scanf("%d", &c);
      G[u][v] = c;
    }
  }
  dijkstra();
  return 0;
}

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

Single Source Shortest Path II

For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$.

Input

In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format:

$u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$

Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$).

Output

For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 10,000$

$0 \leq c_i \leq 100,000$

$|E| < 500,000$

All vertices are reachable from vertex $0$

Sample Input 1

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

Sample Output 1

0 0
1 2
2 2
3 1
4 3

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>

#define tate 3
#define yoko 3
#define Total (tate*yoko)

extern inline void down_0(void);
extern inline void up_0(void);
extern inline void right_0(void);
extern inline void left_0(void);

extern int  serch(int x, int y, int MaxCnt, int pre);
extern int  check(void);

int cnt,num = 0;
int val[Total] ={};

int main( void )
{
    int i = 0;
    int x,y = 0;

    for(i=0; i<Total; i++)
    {
        scanf("%d",&val[i]);

        if(val[i] == 0)
        {
            num = i;
        }
    }

    x = tate - (num/yoko) -1;
    y = yoko - (num%yoko) -1;

    for(i=1; i<20; i++)
    {
        if( serch(x,y,i,4) == 1 )
        {
            printf("%d\n",i);
            break;
        }
    }

    return 0;
}

int serch(int x, int y, int MaxCnt, int pre)
{
    int result;
    int i=0;

    // 最大数で打ち切り
    if(MaxCnt==0)
    {
        return check();
    }

    // 上下左右で4回回す
    for(i=0; i<4; i++)
    {
        result = 0;

        switch(i)
        {
            case 0:
                if( (x > 0) && (pre != 3) )
                {
                    down_0();

                    result = serch(x-1, y, MaxCnt-1, 0);

                    up_0();
                }
                break;
            case 1:
                if( (y > 0) && (pre != 2) )
                {
                    right_0();

                    result = serch(x, y-1, MaxCnt-1, 1);

                    left_0();
                }
                break;
            case 2:
                if( (y < yoko) && (pre != 1) )
                {
                    left_0();

                    result = serch(x, y+1, MaxCnt-1, 2);

                    right_0();
                }
                break;
            case 3:
                if( (x < tate) && (pre != 0) )
                {
                    up_0();

                    result = serch(x+1, y, MaxCnt-1, 3);

                    down_0();
                }
                break;
            default:
                break;
        }

        if(result)
        {
            return 1;
        }

    }

    return 0;
}

// TRUE : 完成
// FALSE : 失敗
int check()
{
    int i=0;

//    printf("%d%d%d%d%d%d%d%d%d\n", val[0], val[1], val[2], val[3], val[4], val[5], val[6], val[7], val[8]);

    for(i=0; i<Total-1; i++)
    {
        if(val[i] != (i+1))
        {
            return 0;
        }
    }
    return 1;
}

inline void down_0()
{
    val[num] = val[num + yoko];
    num = num + yoko;
}

inline void up_0()
{
    val[num] = val[num - yoko];
    num = num - yoko;
}

inline void right_0()
{
    val[num] = val[num +1];
    num = num + 1;
}

inline void left_0()
{
    val[num] = val[num -1];
    num = num - 1;
}

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

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

8 Puzzle

The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.

In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.

1 3 0
4 2 5
7 8 6

You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).

1 2 3
4 5 6
7 8 0

Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.

Input

The $3 \times 3$ integers denoting the pieces or space are given.

Output

Print the fewest steps in a line.

Constraints

There is a solution.

Sample Input

1 3 0
4 2 5
7 8 6

Sample Output

4

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>

#define N 4
#define S 16

typedef struct P{
  int f[S],space,m;
}Puzzle;

int dx[4]={0,-1,0,1};
int dy[4]={1,0,-1,0};

int MDT[S][S];

int limit;
int path[100];
Puzzle st;

int get(Puzzle Z){
  int i,sum=0;
  for(i=0;i<S;i++){
    if(Z.f[i] == S) continue;
    sum+=MDT[i][Z.f[i]-1];
  }
  return sum;
}

int max(int a,int b){
  if(a<b) return b;
  else return a;
}
int min(int a,int b){
  if(a<b) return a;
  else return b;
}
void swap(int *a,int *b){
  int t;
  t=*a;
  *a=*b;
  *b=t;
}

char dfs(int df,int p){
  int sx,sy,tx,ty,i;
  Puzzle tmp;

  if(st.m==0)return 1;
  if(df+st.m>limit)return 0;

  sx=st.space/N;
  sy=st.space%N;

  for(i=0;i<4;i++){
    tx=sx+dx[i];
    ty=sy+dy[i];

    if(tx<0||tx>=N||ty<0||ty>=N) continue;
    if(max(p,i)-min(p,i)==2)continue;
    tmp=st;

    st.m-=MDT[tx*N+ty][st.f[tx*N+ty]-1];
    st.m+=MDT[sx*N+sy][st.f[tx*N+ty]-1];

    //printf("st.m=%d\n",st.m);

    swap(&st.f[tx*N+ty],&st.f[sx*N+sy]);

    st.space=tx*N+ty;
    if(dfs(df+1,i)){
      path[df]=i;
      return 1;
    }
    st=tmp;
  }
  return 0;
}

int id(Puzzle in){
  int i;
  int ans=0;

  in.m=get(in);

  for(limit=in.m;limit<=100;limit++){
      //  printf("aaa\n");
    st=in;
    if(dfs(0,-100)){
      ans=0;;
      for(i=0;i<limit;i++) ans++;
      return ans;
    }
  }
  return -1;
}

int main(){
  int i,j;
  Puzzle in;
  for(i=0;i<S;i++) for(j=0;j<S;j++) MDT[i][j]=abs(i/N-j/N)+abs(i%N-j%N);
  for(i=0;i<S;i++){
    //printf("aaa\n");
    scanf("%d",&in.f[i]);
    if(in.f[i]==0){
      in.f[i]=S;
      in.space=i;
    }
  }
  printf("%d\n",id(in));

  return 0;
}

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

15 Puzzle

The goal of the 15 puzzle problem is to complete pieces on $4 \times 4$ cells where one of the cells is empty space.

In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 15 as shown below.

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

You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).

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

Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.

Input

The $4 \times 4$ integers denoting the pieces or space are given.

Output

Print the fewest steps in a line.

Constraints

The given puzzle is solvable in at most 45 steps.

Sample Input

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

Sample Output

8


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

#define N_T 1000001
#define N_P 10001
#define BASE 64

int* kmpSearch(char*, char*);
int* initNext(char*);

int myIndex(char);

int main() {
  char T[N_T];
  char P[N_P];
  int* pos;

  int i;

  while (scanf("%s %s", T, P) != EOF) {
    pos = kmpSearch(T, P);

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

  return 0;
}

int* kmpSearch(char* T, char* P) {
  int i, j;
  int cnt = 0;
  int M   = strlen(P);
  int N   = strlen(T);

  int* next;
  int* pos;

  if (N < M) {
    pos    = (int*)malloc(sizeof(int)*1);
    pos[0] = 0;
    return pos;
  } else {
    pos = (int*)malloc(sizeof(int)*(N-M+2));
  }

  next = initNext(P);
  for (i = 0, j = 0; i < N; ++i, ++j) {
    while ((j >= 0) && (T[i] != P[j])){
      j = next[j];
    }

    if (j == M - 1) {
      cnt++;
      pos[cnt] = i - M + 1;

      do {
	j = next[j];
      }	while ((j >= 0) && (T[i] != P[j]));
    }
  }
  pos[0] = cnt;

  return pos;
}

int* initNext(char* P){
  int i, j;
  int M = strlen(P);
  int* next = (int*)malloc(sizeof(int)*M);

  next[0] = -1;
  for (i = 0, j = -1; i < M; ++i, ++j, next[i] = j) {
    while ((j >= 0) && (P[i] != P[j])) {
      j = next[j];
    }
  }

  return next;
}

String Search

Find places where a string P is found within a text T.
Print all indices of T where P found. The indices of T start with 0.

Input

In the first line, a text T is given. In the second line, a string P is given.

Output

Print an index of T where P found in a line. Print the indices in ascending order.

Constraints

1 ≤ length of T ≤ 1000000

1 ≤ length of P ≤ 10000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
aa

Sample Output 1

0
3
4

Sample Input 2

xyzz
yz

Sample Output 2

1

Sample Input 3

abc
xyz

Sample Output 3

The output should be empty.


Insertion Sort

Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

for i = 1 to A.length-1
key = A[i]
/* insert A[i] into the sorted sequence A[0,...,j-1] */
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j--
A[j+1] = key

Note that, indices for array elements are based on 0-origin.

To illustrate the algorithms, your program should trace intermediate result for each step.

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 a single space.

Output

The output consists of N lines. Please output the intermediate sequence in a line for each step. Elements of the sequence should be separated by single space.

Constraints

1 ≤ N ≤ 100

Sample Input 1

6
5 2 4 6 1 3

Sample Output 1

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

Sample Input 2

3
1 2 3

Sample Output 2

1 2 3
1 2 3
1 2 3

Hint

Template in C


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

int sosudiagnosis(int);

int main()
{
  int n; //入力できる個数
  int s; //数
  int l=0; //ループの回数
  int count=0;//素数の数

  scanf("%d",&n);
  while(l < n){
    l++;
    scanf("%d",&s);

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

int sosudiagnosis(int s)
{
  int i=3;
  if(s == 2) return 1;

  if(s < 2 || s%2==0) return 0;

  while(i <= sqrt(s)){
    if(s%i==0) return 0;

    i = i + 2;
  }
  return 1;
}

Prime Numbers

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a program which reads a list of N integers and prints the number of prime numbers in the list.

Input

The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output

Print the number of prime numbers in the given list.

Constraints

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

11
7
8
9
10
11
12
13
14
15
16
17

Sample Output 2

4


#include<stdio.h>
int main(void){
int i,x,sum=0;
long int n;
scanf("%d",&i);
for(x=0;x<i;x++){
scanf("%ld",&n);
if(1==IsPrime(n)){sum+=1;}
}
printf("%d\n",sum);
return 0;
}

int IsPrime(long int n){
    int i;

    if(n < 2)
        return 0;
    else if(n == 2)
        return 1;

    if(n % 2 == 0)
        return 0;

    for(i = 3; i <= n / i; i += 2)
         if(n % i == 0)
            return 0;
    return 1;
}


#include <stdio.h>

int PRIMES[100000000] = {0};

void make_prime() {
	PRIMES[0] = 2;
	int i, j;

	for (i = 3; i < 10000; ++i) {
		for (j = 0; PRIMES[j] != 0; ++j) {
			if ((i % PRIMES[j]) == 0) {
				break;
			}
		}
		if (PRIMES[j]) {
			continue;
		} else {
			PRIMES[j] = i;
		}
	}
	return;
}

int main(void)
{
	int i, j, n, cnt, p;
	make_prime();
	scanf("%d", &n);
	cnt = 0;
	for (i = 0; i < n; ++i) {
		scanf(" %d", &p);
		for (j = 0; PRIMES[j] <= p; ++j) {
			if (PRIMES[j] == p) {
				++cnt;
				break;
			}
		}
	}

	printf("%d\n", cnt);
	return 0;
}


#include <stdio.h>

int main(void)
{
	int i; //割る
	int n; //入力された自然数
	int prime[10000];
	int j = 0;
	int counter = 0; //素数の個数

	prime[j++] = 2;
	prime[j++] = 3;

	scanf("%d", &n);

	for (n = 5; n <= 100000; n += 2) {
		for (i = 1; i < j; i++) {
			if (n % prime[i] == 0)
				break;

		}
		if (j == i)
			prime[j++] = n;
	}

	for (i = 0; i < j; i++)
		counter++;

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

	return(0);

}


#include<stdio.h>
#define N 10000

int main(){
  int i=0,A[N],count=0,count2=0,n,k;

  scanf("%d",&n);
  for(i=0;i<n;i++) scanf("%d",&A[i]);
  for(i=0;i<n;i++){
    for(k=2,count2=0;k<A[i];k++){
      if(A[i]%k==0){
	count2++;
	break;}}
    if(count2==0) count++;
  }
  printf("%d\n",count);
  return 0;
}


#include<stdio.h>
#include<math.h>
int main()
{
  int l,x,i,j,k=0;

  scanf("%d",&l);

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

      for(j=2;j<=sqrt(x);j++)
	{
	  if(x%j==0){ k++; break;}
	}

    }

  printf("%d\n",l-k);

  return 0;
}


#include <stdio.h>
int main(){
    int n, i;
    scanf("%d", &n);
    int input, primes = 0;
    for(i = 0; i < n; i++){
        scanf("%d", &input);
        if(isPrime(input)) primes++;
    }
    printf("%d\n", primes);
}
int isPrime(int test){
    if (test==2) return 1;
    for (int i = 2; i <= test/i; i++){
        if (test%i==0) return 0;
    }
    return 1;
}


#include <stdio.h>
#include <limits.h>
#define N 200001
#define imax(a,b) (a>b)?a:b
#define imin(a,b) (a<b)?a:b

int main()
{
  int n,r;
  scanf("%d",&n);
  int ans=INT_MIN,rmin;

  int i;
  for(i=0;i<n;i++){
    scanf("%d",&r);
    if(i==0) rmin=r;
    else{
      ans=imax(ans,r-rmin);
      rmin=imin(r,rmin);
    }
  }

  printf("%d\n",ans);
  return 0;
}

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

Maximum Profit

You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.

Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ .

Input

The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order.

Output

Print the maximum value in a line.

Constraints

$2 \leq n \leq 200,000$

$1 \leq R_t \leq 10^9$

Sample Input 1

6
5
3
1
3
4
3

Sample Output 1

3

Sample Input 2

3
4
3
2

Sample Output 2

-1


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

static const int MAX_NUM_INPUT = 200000;
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))

int main()
{
    int n, i;
    int R[MAX_NUM_INPUT];
    int maxv = INT_MIN;
    int minv;

    scanf("%d", &n);

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

    minv = R[0];

    for (i = 1; i < n; i++) {
        maxv = MAX(maxv, R[i] - minv);
        minv = MIN(minv, R[i]);
    }

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

    return 0;
}


#include<stdio.h>
int minnum(int[], int);

int main(){
  int n, i, j, max, min;
  int R[200000];
  scanf("%d",&n);
  for( i = 0 ; i < n ; i++ ){
    scanf("%d",&R[i]);
  }

  min = R[0];
  max = R[1] - R[0];
  for( i = 1 ; i < n ; ++i ){
    if( max < R[i]-min ) max = R[i]- min;
    if( min > R[i] ) min = R[i];
  }

  printf("%d\n",max);
  return 0;
}


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

#define N 200000

int main(void){
  int n;
  int r[N];
  int i;
  int maxv = -1 * 1000000000;

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

  int minv = r[0];

  for(i = 1; i <= n - 1; i++){
    if(maxv < r[i] - minv){
      maxv = r[i] - minv;
    }
    if(minv > r[i]){
      minv = r[i];
    }
  }

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

}


#include <stdio.h>

int main(){
    int N, Array[200001], max, minSub;
    scanf("%d\n",&N);
    for (int ix = 0 ; ix < N ; ix++)
        scanf("%d",&Array[ix]);
    max = Array[1] - Array[0];
    minSub = Array[0];
    for (int jx = 1 ; jx < N ; jx++){
        if (max < Array[jx] - minSub)
            max = Array[jx] - minSub;
        if ( minSub > Array[jx])
            minSub = Array[jx];
    }

  printf("%d\n",max);
  return 0;
}


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

  int stack[100];
  char str[100];
  int top=0,i;
  int ch;
  for (i=0;i<100;i++){
    stack[i]=0;
  }
  while (scanf("%s",str)!='\n'){
    if (str[0]=='+'){
      stack[top-2]=stack[top-2]+stack[top-1];
      top=top-1;
    }else if(str[0]=='*'){
      stack[top-2]=stack[top-2]*stack[top-1];
      top=top-1;
    }else if(str[0]=='-'){
      stack[top-2]=stack[top-2]-stack[top-1];
      top=top-1;
    }else{
      stack[top]=atoi(str);
      top++;
    }
  }
  printf("%d\n",stack[top-1]);
  return 0;
}

Reverse Polish notation is a notation where every operator follows all of its operands. For example, an expression (1+2)*(5+4) in the conventional Polish notation can be represented as 1 2 + 5 4 + * in the Reverse Polish notation. One of advantages of the Reverse Polish notation is that it is parenthesis-free.

Write a program which reads an expression in the Reverse Polish notation and prints the computational result.

An expression in the Reverse Polish notation is calculated using a stack. To evaluate the expression, the program should read symbols in order. If the symbol is an operand, the corresponding value should be pushed into the stack. On the other hand, if the symbols is an operator, the program should pop two elements from the stack, perform the corresponding operations, then push the result in to the stack. The program should repeat this operations.

Input

An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.

You can assume that +, - and * are given as the operator and an operand is a positive integer less than 106

Output

Print the computational result in a line.

Constraints

2 ≤ the number of operands in the expression ≤ 100

1 ≤ the number of operators in the expression ≤ 99

-1 × 109 ≤ values in the stack ≤ 109

Sample Input 1

1 2 +

Sample Output 1

3

Sample Input 2

1 2 + 3 4 - *

Sample Output 2

-3

Notes

Template in C


#include <stdio.h>
#include <string.h>
#define LEN 100005
typedef struct pp{
	char name[10];
	int t;
}P;

P Q[LEN];
int head,tail,n;

void enqueue(P);
P dequeue();
int min(int,int);

int main(void){
	int elaps=0,c;
	int i,q;
	P u;
	scanf("%d %d",&n,&q);

	for(i=1;i<=n;i++){
		scanf("%s",Q[i].name);
		scanf("%d",&Q[i].t);
	}
	head=1,tail=n+1;

	while(head!=tail){
		u=dequeue();
		c=min(q,u.t);
		u.t -= c;
		elaps += c;
		if(u.t>0){
			enqueue(u);
		}else{
			printf("%s %d\n",u.name,elaps);
		}
	}

	return 0;
}

void enqueue(P x){
	Q[tail]=x;
	tail=(tail+1)%LEN;
}

P dequeue(){
	P x=Q[head];
	head=(head+1)%LEN;
	return x;
}
int min(int a,int b){
	if(a<b){
		return a;
	}else{
		return b;
	}
}

There are n processes in a queue. Each process has namei and timei. The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue.

For example, we have the following queue with the quantum of 100ms.

A(150) - B(80) - C(200) - D(200)

First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms).

B(80) - C(200) - D(200) - A(50)

Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue.

C(200) - D(200) - A(50)

Your task is to write a program which simulates the round-robin scheduling.

Input

n q

name1 time1

name2 time2

...

namen timen

In the first line the number of processes n and the quantum q are given separated by a single space.

In the following n lines, names and times for the n processes are given. namei and timei are separated by a single space.

Output

For each process, prints its name and the time the process finished in order.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 1000

1 ≤ timei ≤ 50000

1 ≤ length of namei ≤ 10

1 ≤ Sum of timei ≤ 1000000

Sample Input 1

5 100
p1 150
p2 80
p3 200
p4 350
p5 20

Sample Output 1

p2 180
p5 400
p1 450
p3 550
p4 800

Notes

Template in C


#include <stdio.h>
#include <string.h>
#define MAX 100005

typedef struct Proc {
    char name[20];
    int time;
} P;

P Q[MAX];
int head, tail, n;

void enqueue(P x)
{
    Q[tail] = x;
    tail = (tail + 1) % MAX;
}

P dequeue()
{
    P x = Q[head];
    head = (head + 1) % MAX;
    return x;
}

int min(int a, int b)
{
    return a < b ? a : b;
}

int main()
{
    int elaps = 0, c;
    int i, q;
    P u;
    scanf("%d %d", &n, &q);

    for (i = 1; i < n+1; i++) {
        scanf("%s", Q[i].name);
        scanf("%d", &Q[i].time);
    }
    head = 1;
    tail = n + 1;

    while (head != tail) {
        u = dequeue();
        c = min(q, u.time);
        u.time -= c;
        elaps += c;
        if (u.time > 0) {
            enqueue(u);
        } else {
            printf("%s %d\n", u.name, elaps);
        }
    }

    return 0;
}


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

/*-----------構造体定義-----------------*/
typedef struct node{
 int num;
 struct node *left;
 struct node *right;
}node;
/*--------------------------------------*/

/*-----------------要素作成-------------*/
node* makenode(int x){
node* new;

new=(node*)malloc(sizeof(node));
new->num=x;
new->right=NULL;

return new;
}
/*-------------------------------------*/

int main(){
int n,i,x;
int y=1;
char com[13];
node* root;
node* p;
node** q;
node* r;
root=NULL;

scanf("%d",&n);

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

 if(com[0]=='i'){
   scanf("%d",&x);
   p=makenode(x);
    if(root!=NULL){
        root->left=p;
        p->right=root;
        root=p;
    }else{root=p;}
 }else
 if(strcmp(com,"deleteFirst")==0){
   if(root->right==NULL){free(root);root=NULL;}
   else{root->right->left=NULL;
        root=root->right;}
  }else
  if(strcmp(com,"deleteLast")==0){
   if(root->right==NULL){root=NULL;}
   else{q=&(root->right);
    while((*q)!=NULL){
     if((*q)->right==NULL){(*q)=NULL;}
     else{q=&((*q)->right);}
    }
   }
  }else

if(strcmp(com,"delete")==0){
   scanf("%d",&x);

/*要素1つの場合*/
if(root->right==NULL){if(root->num==x)root=NULL;}

/*要素が2以上*/
else{

  if(root->num==x){/*先頭*/
       root->right->left=NULL;
       root=root->right;}

  else{p=root;

      while(p!=NULL){

        if(p->num==x){

          if(p->right==NULL){p->left->right=NULL;break;}
          else{

            p->right->left=p->left;
            p->left->right=p->right;
            p->right=NULL;}
        }

        p=p->right;

       }/*while終了*/

   }
}
}
}
p=root;
while(p!=NULL){

if(p->right==NULL){printf("%d\n",p->num);}
else{printf("%d ",p->num);}
p=p->right;

}

return 0;
}

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


#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;
void insert(int key);
int delete(int key);
int deleteFirst();
int deleteLast();
void init();     /* This fanction is initializing nil. */

main(){
  int n, i, keydata;
  char com[12];
  NodePointer p;
  scanf("%d",&n);
  nil=malloc(sizeof(struct node));
  init();

  for (i=0;i<n;i++){
    scanf("%s",com);
    if(strlen(com)>6){
      if(com[6]=='F') {
        deleteFirst();
      }else{
        deleteLast();
      }
    }else{
      scanf("%d",&keydata);
      if(com[0]=='i'){
        insert(keydata);
      }else{
        delete(keydata);
      }
    }
  }

  for(p=nil->next;p!=nil->prev;p=p->next){
    printf("%d ",p->key);
  }
  printf("%d\n",p->key);
  free(nil);
  return 0;
}

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

int delete(int keydata){
  NodePointer p;
  p=nil->next;
  while(p!=nil&&p->key!=keydata){
    p=p->next; /* search */
  }
  if(p==nil){  /* If not found, this function is forced termination.  */
    return 0;
  }else{
    p->prev->next=p->next;
    p->next->prev=p->prev;
    free(p);
    return 0;
  }
}

int deleteFirst(){
  NodePointer p;
  p=nil->next;
  nil->next=p->next;
  p->next->prev=nil;
  free(p);
  return 0;
}

int deleteLast(){
  NodePointer p;
  p=nil->prev;
  p->prev->next=nil;
  nil->prev=p->prev;
  free(p);
  return 0;
}

void init(){
  nil->next=nil;
  nil->prev=nil;
}


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

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

typedef struct node * NodePointer;

NodePointer nil;

NodePointer listSearch(int key){
  NodePointer x;
  x = nil->next;
  while(x != nil && x->key != key) x = x->next;

  return x;
}

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

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;
  t = listSearch(key);
  if(t == nil) return;
  deleteNode(t);
}

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

  if(nil->next == nil) nil->prev = x;
  x->next = nil->next;
  nil->next->prev =x;
  nil->next = x;
  x->prev = nil;
}

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%d", com, &key);
    if ( com[0] == 'i' ) {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 {
	delete(key); nd++;
      }
      size--;
    }
  }

  printList();
  return 0;
}


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

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

typedef struct node * NodePointer;

NodePointer nil;

NodePointer listSearch(int key){
  NodePointer cur = nil->next;
  while (cur != nil && cur->key != key) {
      cur = cur->next;
  }
  return cur;
}

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){
    if ( t == nil) return ;
    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(){
  deleteNode(nil->prev);
}

void delete(int key){
    deleteNode(listSearch(key));
}

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

    x->next = nil->next;
    nil->next->prev = x;
    nil->next = x;
    x->prev = nil;
}

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%d", com, &key);
    if ( com[0] == 'i' ) {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 {
	delete(key); nd++;
      }
      size--;
    }
  }
  printList();
  return 0;
}


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

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

struct node *null;

struct node *listSearch(int key)
{
	struct node *cur = null->next;
	while(cur!=null&&cur->key!=key)
	{
		cur =cur->next;
	}
	return cur;
}

void init(){

	null=(struct node*)malloc(sizeof(struct node));
	null->next=null;
	null->prev=null;
}

void printList()
{
	struct node *cur=null->next;
	int isf=0;
	while(cur!=null)
	{
		if(isf++)putchar_unlocked(' ');
		printf("%d",cur->key);
		cur=cur->next;
	}
	putchar_unlocked('\n');
}

void deleteNode(struct node *t)
{
if(t==null) return;
t->prev->next=t->next;
t->next->prev=t->prev;
free(t);
}
void deleteFirst()
{
	deleteNode(null->next);
}
void deleteLast()
{
	deleteNode(null->prev);
}
void deleteKey(int key)
{
	deleteNode(listSearch(key));
}

void insert(int key)
{
	struct node *x=(struct node*)malloc(sizeof(struct node));
	x->key=key;
	x->next=null->next;
	null->next->prev=x;
	null->next=x;
	x->prev=null;
}
int main(void)
{
	int key,n,i;
	char com[20];
	null=(struct node*)malloc(sizeof(struct node));
	null->next=null;
	null->prev=null;

	scanf("%d",&n);

	for(i=0;i<n;i++)
	{
		scanf("%s",com);
		if(strlen(com)>6)
		{
			if(com[6]=='F')
			{
				deleteFirst();
			}
			else
			{
				deleteLast();
			}
		}
		else
		{
			scanf("%d",&key);

			if(com[0]=='d')
				{
					deleteKey(key);
				}
			else
			{
				insert(key);
			}

		}
	}
	printList();
	return 0;
}


#include<stdio.h>

//void linearSearch(int);

int main (){

  int n,q,i,j,count=0;
  int S[100000];
  int T[50000];

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

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

  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>
#include<stdlib.h>

int main(){
  int n,q;
  int *S,*T,B[1000000];
  int i,u;
  int l,m,r;
  int count=0,flag,key;

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

  for(i=0;i<q;i++){
    key=T[i];
    l=0;
    r=n+2;
    m=(r+l)/2;
    flag=0;

    for(u=0;u<count;u++){
      if(B[u]==key){
	flag=1;
	break;
      }
    }

    while(r>l){
      if(flag==1) break;
      if(key==S[m]){
	B[count++]=key;
	break;
      }
      else if(key<S[m]){
	r=m;
	m=(r+l)/2;
      }else if(key>S[m]){
	l=m+1;
	m=(r+l)/2;
      }
    }

  }

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

  free(S);
  free(T);
  return 0;
}


#include <stdio.h>

int A[20];
int solve(int i, int m, int n) {
  int res;
  if (m == 0) {
    return 1;
  } else if (i >= n) {
    return 0;
  } else {
    res = solve(i + 1, m, n) || solve(i + 1, m - A[i], n);
    return res;
  }
}

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

  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], n) == 1) {
      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>

int solve(int,int,int *,int);

int main()
{
  int i,n,A[21],q,m;

  scanf("%d",&n);
  for(i=1;i<=n;i++){
    scanf("%d",&A[i]);
  }
  scanf("%d",&q);
  for(i=1;i<=q;i++){
    scanf("%d",&m);
  if(solve(1,m,A,n))printf("yes\n");
  else printf("no\n");
  }
  return 0;
}

int solve(int i,int m,int A[],int n)
{
  int res;

  if(m == 0)return 1;
  if(i > n)return 0;

  res = solve(i + 1,m,A,n) || solve(i + 1,m - A[i],A,n);

  return res;
}


#include<stdio.h>
int n,A[50];
int sol(int i, int m){
  if(m==0) return 1;
  if(i>=n) return 0;
  int res=sol(i+1,m)||sol(i+1,m-A[i]);
  return res;
}
int main()
{
  int q,M,i;
  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);
    if(sol(0,M)) printf("yes\n");
    else printf("no\n");
  }
  return 0;
}


#include <stdio.h>

void del_element(int *a,int i,int n, int* temp){
    int j,k=0;
    for(j=0;j<n;j++){
        if(j!=i){
            temp[k]=a[j];
            k++;
        }
    }
}

int solve(int *a,int n,int m){
    if (m == 0) return 1;
    if (m < 0) return 0;
    int i;
    int calc=0;
    int temp[21];

    for(i=0;i<n;i++){
        calc=a[i];
        if(calc==m){
            return 1;
        }
        else{
            del_element(a,i,n,temp);
            if(solve(temp,n-1,m-calc)==1){
                return 1;
            }
        }
    }
    return 0;
}

int main(){
    int n,q,m[201];
    int A[21];
    scanf("%d",&n);
    int i;
    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(A,n,m[i])==1){
            printf("yes\n");
        }
        else{
            printf("no\n");
        }
    }
    return 0;
}


#include<stdio.h>

int n, A[50];

int Ex_search (int i, int m);

int main(){
  int q,M,i;

  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);
    if(Ex_search(0,M))printf("yes\n");
    else printf("no\n");
  }

  return 0;
}

int Ex_search (int i, int m){
  if(m==0)return 1;
  if(i>=n)return 0;
  int res= Ex_search(i+1,m)||Ex_search(i+1,m-A[i]);
  return res;
}


#include <stdio.h>

int A[20];
int n;

int solve(int p, int t);
int sort(void *a, void *b);

int main(void) {
	int i, q, M, j;

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

	qsort(A, n, sizeof(A[0]), sort);

	scanf("%d", &q);
	for (i = 0; i < q; ++i) {
		scanf("%d", &M);
		for (j = 0; A[j] > M; ++j);
		if (solve(j - 1, M)) {
			printf("yes\n");
		} else {
			printf("no\n");
		}
	}

	return 0;
}

int solve(int p, int t) {
	if ((p == n) || (t == 0)) return t == 0;
	if ((t >= A[p + 1]) && (solve(p + 1, t - A[p + 1]))) return 1;
	return solve(p + 1, t);
}

int sort(void *a, void *b) {
	return *(int*)b - *(int*)a;
}


#include<stdio.h>

#define N 2000

void solve(int,int);

int A[N];
int M[N];
int n,flag=0;

int main(){
  int i,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++){
    flag = 0;
    solve(0,M[i]);
    if(flag == 1){
      printf("yes\n");
    }else{
      printf("no\n");
    }
  }

  return 0;
}

void solve(int i,int m){
  if(m == 0){
    flag = 1;
  }else if(i < n){
    solve(i+1,m-A[i]);
    solve(i+1,m);
  }
}


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

#define N 20
int solve(int,int);

int n;
int A[N];

int main()
{
  int q,i,j = 0;
  scanf("%d",&n);
  for(i = 0;i < n;i++)
    {
      scanf("%d",&A[i]);
    }
  scanf("%d",&q);
  int M[q];
  for(i = 0;i < q;i++)
    {
      scanf("%d",&M[i]);
    }
  for(i = 0;i < q;i++)
    {
      if(solve(j,M[i]) == 1)
	{
	  printf("yes\n");
	}
      else
	{
	  printf("no\n");
	}
    }
}

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


#include <stdio.h>
#define INFTY 500000
int L[INFTY],R[INFTY],A[INFTY],count=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++){
    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;
      scanf("%d",&N);
      for(i=0;i<N;i++){
	scanf("%d",&A[i]);
      }
      mergeSort(A,0,N);

      for(i=0;i<N;i++){
	if(i!=0)printf(" ");

	printf("%d",A[i]);
      }
      printf("\n");
      printf("%d\n",count);
        return 0;
    }

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 500000
#define SENTINEL 2000000000
int L[MAX/2+2],R[MAX/2+2];
int count;
void merge(int[],int,int,int,int);
void mergeSort(int[],int,int,int);
int main(){
  int A[MAX],n,i;
  count=0;
  scanf("%d",&n);
  for(i=0;i<n;i++)
    scanf("%d",&A[i]);
  mergeSort(A,n,0,n);
  for(i=0;i<n;i++){
    printf("%d",A[i]);
    if(i==n-1){
      printf("\n");
      break;
    }
    printf(" ");
  }
  printf("%d\n",count);
  return 0;
}
void merge(int A[],int n,int left,int mid,int right){
  int i,j,k,n1,n2;
  n1=mid-left;
  n2=right-mid;
  for(i=0;i<n1;i++)
    L[i]=A[left+i];
  for(j=0;j<n2;j++)
    R[j]=A[mid+j];
  L[n1]=SENTINEL;
  R[n2]=SENTINEL;
  i=0;
  j=0;
  for(k=left;k<right;k++){
    count++;
    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 n,int left,int right){
  int mid;
  if(left+1<right){
    mid=(left + right)/2;
   mergeSort(A,n,left,mid);
    mergeSort(A,n,mid,right);
    merge(A,n,left,mid,right);
  }
}


#include <stdio.h>
#define MAX 500000
#define INFTY 1000000001

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

void merge(int *A, int left, int mid, int right) {
  int i, j, k;
  int n1 = mid - left;
  int n2 = right - mid;
  //L[0...n1], R[0...n2] を生成
  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++) {
    count++;
    if (L[i] <= R[j]) {
      A[k] = L[i];
      i++;
    } else {
      A[k] = R[j];
      j++;
    }
  }
}

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

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

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


#include <stdio.h>
#include <stdlib.h>
#define  MAX 500000
#define INFTY 100000000
int S[MAX],count=0;

void merge(int A[], int left,int mid, int right)
{
  int n1,n2,i,j,k;
  int *L,*R;
  n1 = mid - left;
  n2 = right - mid;
  L = (int *)malloc(sizeof(int)*(n1+1));
  R = (int *)malloc(sizeof(int)*(n2+1));
  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++){
    if(L[i] <= R[j]){
      A[k] = L[i];
      i++;
      count++;
    }
    else{
      A[k] = R[j];
      j++;
      count++;
    }
  }
  free(L);
  free(R);
}

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;
  scanf("%d",&n);
  for(i = 0;i < n;i++)
    scanf("%d",&S[i]);
  mergeSort(S,0,n);
  for(i = 0;i < n;i++){
    printf("%d",S[i]);
    if(i < n-1) printf(" ");
  }
  printf("\n");
  printf("%d\n",count);
  return 0;
}


#include <stdio.h>
#define MAX 500000
#define INFTY 2000000000

int count;

void merge(int A[], int left, int mid, int right){
  int i, j , k, n1, n2;
  int L[MAX/2+2], R[MAX/2+2];

  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++){
    count++;
    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=0;

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

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

  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) break;
    printf(" ");
  }
  printf("\n");
  printf("%d\n", count);

  return 0;
}


#include<stdio.h>
#define MAX 500000
int cou=0;
void mergeSort(int *,int,int);
void merge(int *,int,int,int);
int main(){
  int i,n,S[MAX];

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

  mergeSort(S,0,n);

  for(i=0;i<n;i++){
    printf("%d",S[i]);
    if(i!=n-1)printf(" ");
  }
  printf("\n%d\n",cou);
  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 n1=mid-left,n2=right-mid;
  int i,j,L[250000],R[250000],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]=R[n2]=20000;

  i=j=0;

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

  }
}


#include<stdio.h> //mergesort
#define N 500000
#define M 2000000000

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

void merge(int A[],int l,int m,int r)
{
  int i,j,k;
  int n1;
  int n2;

  n1 = m - l;
  n2 = r - m;

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

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

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

void mergesort(int A[],int l,int r)
{
  int m;
  if(l+1<r)
    {
      m = (l+r)/2;
      mergesort(A,l,m);
      mergesort(A,m,r);
      merge(A,l,m,r);
    }
}

int main()
{
  int i,a,b[N];

  scanf("%d",&a);

  for(i=0;i<a;i++)
    {
      scanf("%d",&b[i]);
    }
  mergesort(b,0,a);
  for(i=0;i<a-1;i++)
    {
      printf("%d ",b[i]);
    }
  printf("%d\n",b[a-1]);
  printf("%d",count);
  printf("\n");

  return 0;
}


#include<stdio.h>

#define Max 500000
#define Sen 1000000000

int count;
int l[Max / 2 + 2], r[Max / 2 + 2];

void merge(int a[], int n, 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] = r[n2] = Sen;

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

void mergeSort(int a[], int n, int left, int right){
  if(left + 1 < right){
    int mid;

    mid = (left + right) / 2;
    mergeSort(a, n, left, mid);
    mergeSort(a, n, mid, right);
    merge(a, n, left, mid, right);
  }
}

int main(){
  int a[Max], n, i;
  count = 0;

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

  mergeSort(a, n, 0 , n);

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

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

  return 0;
}


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

#define N 500000
#define SENTINEL 1000000000

int num,L[N/2+2],R[N/2+2];
int cnt=0;

void merge(int [],int,int,int);
void mergeSort(int [],int,int);

int main(){
    int i,j;
    int l,m,r;
    int A[N];

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

    mergeSort(A,0,num);
    for(i=0;i<num;i++){
        if(i) printf(" ");
        printf("%d",A[i]);
    }
    printf("\n");
    printf("%d\n",cnt);
    return 0;
}

void merge(int A[],int l,int m,int r){
    int n1,n2;
    int i,j,k;

    n1 = m-l;
    n2 = r-m;

    for(i=0;i<n1;i++){
        L[i] = A[l+i];
    }
    for(j=0;j<n2;j++){
        R[j] = A[m+j];
    }
    L[n1] = SENTINEL;
    R[n2] = SENTINEL;

    i=j=0;
    for(k=l;k<r;k++){
        cnt++;
        if(L[i] <= R[j]){
            A[k] = L[i];
            i++;
        }
        else{
            A[k] = R[j];
            j++;
        }
    }
}

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


#include <stdio.h>

int count = 0;

void merge(int a[], int left, int mid, int right) {
	int n1 = mid - left;
	int n2 = right - mid;
	int L[n1], R[n2];
	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] = 1000000001; //Inf
	R[n2] = 1000000001; //Inf
	i = 0;
	j = 0;
	for (k = left; k < right; k++) {
		count++;
		if (L[i] <= R[j]) {
			a[k] = L[i];
			i++;
		}
		else {
			a[k] = R[j];
			j++;
		}
	}
}

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(void) {
	int a[500000];
	int n, i;

	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) {
			putchar(' ');
		}
	}
	putchar('\n');
	printf("%d\n", count);

	return 0;
}


#include<stdio.h>

int count=0;
void margesort(int *,int,int);
void marge(int *,int,int,int);

int S[2000000],L[100001],R[100001];

int main(){
  // FILE* p;
  int n,i;
  // p=fopen("ALDS1_5_D_in.txt","r");
  //fscanf(p,"%d",&n);
  scanf("%d",&n);
  for(i=0;i<n;i++) //fscanf(p,"%d",&S[i]);
    scanf("%d",&S[i]);
   margesort(S,0,n);

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

   //fclose(p);

   return 0;
}

void margesort(int *S,int left,int right){
  int mid;
  if(left+1 < right){
    mid = (left + right)/2;
    margesort(S,left,mid);
    margesort(S,mid,right);
    marge(S,left,mid,right);
  }
}

void marge(int *S,int left,int mid,int right){
  int n1,n2;
  int i,j=0,k;

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

  for(i=0;i<n1;i++) L[i] = S[left+i];
  L[n1]=-1;
  for(i=0;i<n2;i++) R[i] = S[mid+i];
  R[n2]=-1;

  i=0;
  for(k=left;k<right;k++){
  if(L[i] > R[j]){
    S[k] = L[i];
    i++;
    count += n2 - j;
  }
  else{
    S[k] = R[j];
    j++;
  }
  }
}

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>
#include <stdlib.h>
long long merge(int *,int,int,int);
long long mergesort(int*,int,int);
int main(){
  int A[200000],i,n;
  scanf("%d",&n);
  for(i=0;i<n;i++)scanf("%d",&A[i]);
  long long cnt=mergesort(A,0,n);
  printf("%d\n",cnt);
  return 0;
}
long long merge(int *a,int left,int mid,int right){
  long long cnt=0;
  int l,i,k,j,n1=mid-left,n2=right-mid;
  int *L,*R;
  L=malloc(sizeof(int)*(n1+2));
  R=malloc(sizeof(int)*(n2+2));
  for(i=0;i<n1;i++){
    L[i]=a[left+i];
  }
  for(i=0;i<n2;i++){
    R[i]=a[mid+i];
  }
  L[n1]=2147483647;
  R[n2]=2147483647;
  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;
    }
  }
  free(L);
  free(R);
  return cnt;
}
long long  mergesort(int *a,int left,int right){
  int mid;
  long long v1,v2,v3;
  if(left+1<right){
    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;
}


#include<stdio.h>
#include<stdlib.h>
void countingsort(int n,int a[],int b[],int k){
  int i,j,c[k+1];
  for(i=0;i<=k;i++)c[i]=0;
  for(j=1;j<=n;j++)c[a[j]]++;
  for(i=1;i<=k;i++)c[i]=c[i]+c[i-1];
  for(j=n;j>=1;j--){
    b[c[a[j]]]=a[j];
    c[a[j]]--;
  }
}

int main(){
  int n,*a,i,*b,k=0;

  scanf("%d",&n);
  a=(int *)malloc(n*sizeof(int));
  b=(int *)malloc(n*sizeof(int));
  for(i=1;i<=n;i++){
    scanf("%d",&a[i]);
    if(k<a[i])k=a[i];
  }
  countingsort(n,a,b,k);
  for(i=1;i<n;i++)printf("%d ",b[i]);
  printf("%d\n",b[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>

#define AMAX 2000000
#define BCMAX 10000

int gn;

void countingSort( int A[], int B[], int k )
{
	long long i,j;
	int C[BCMAX+1];

	for( i=0; i<=k; i++ ) {
		C[i]=0;
	}
	for( j=1; j<=gn; j++ ) {
		C[ A[j] ]=C[ A[j] ]+1;
	}
	for( i=1; i<=k; i++ ) {
		C[i]=C[i]+C[ i-1 ];
	}
	for( j=gn; 0<j; j-- ) {
		B[ C[ A[j] ] ]=A[j];
		C[ A[j] ]=C[ A[j] ]-1;
	}

	return;
}

int main( void )
{
	long long i;
	int A[AMAX+1];
	int B[BCMAX+1];
	int k;

    scanf( "%d", &gn );

	k=0;
	for( i=1; i<=gn; i++ ) {
		scanf( "%d", &A[i] );
		if( k < A[i] ) {
			k=A[i];
		}
	}
	countingSort( A, B, k );
	for( i=1; i<=gn; i++ ) {
		printf( "%d", B[i] );
		if( i < gn ) {
			printf( " " );
		}
	}
	printf( "\n" );

    return 0;
}


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

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

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

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

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

  for(i=0;i<n;i++){
    scanf("%d",&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>
#define MAX 100000
#define VMAX 100000

int main(){
  unsigned short *A;
  int n, i, j,x,temp;

  scanf("%d", &n);

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

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

  x=A[n-1];
  i=-1;
  for(j=0; j<n-1; j++){
      if(A[j]<=x){
          i++;
          temp=A[j];
          A[j]=A[i];
          A[i]=temp;
      }
  }
  temp=A[i+1];
  A[i+1]=A[n-1];
  A[n-1]=temp;

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

  return 0;
}

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>
#include <stdlib.h>

#define false 0
#define true 1

#define INFTY 2147483647

void swapInt( int *n1, int *n2) {

  int tmp;

  tmp = *n1;
  *n1 = *n2;
  *n2 = tmp;

}

void swapChar( char *c1, char *c2) {

  char tmp;

  tmp = *c1;
  *c1 = *c2;
  *c2 = tmp;

}

int partition( int *a, char *c, int p, int r) {

  int x;
  int i, j;

  x = a[r];
  i = p-1;

  for( j=p; j<r; j++) {
    if( a[j] <= x ) {
      i++;
      swapInt( &a[i], &a[j]);
      swapChar( &c[i], &c[j]);
    }
  }
  swapInt( &a[i+1], &a[r]);
  swapChar( &c[i+1], &c[r]);
  return i+1;

}

quickSort(int*  a, char* c, int p, int r) {

  int q;

  if( p < r) {
    q = partition( a, c, p, r);
    quickSort( a, c, p, q-1);
    quickSort( a, c, q+1, r);
  }
}

void merge( int* a, char* c, int left, int mid, int right) {

  int *l, *r;
  char *lc, *rc;
  int n1, n2;

  int i, j, k;

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

  l = (int *)malloc(sizeof(int) *(n1+1));
  lc = (char *)malloc(sizeof(char) *(n1+1));
  r = (int *)malloc(sizeof(int) *(n2+1));
  rc = (char *)malloc(sizeof(char) *(n1+1));

  for( i=0; i<n1; i++) {
    l[i] = a[left+i];
    lc[i] = c[left+i];
  }
  for( i=0; i<n2; i++) {
    r[i] = a[mid+i];
    rc[i] = c[mid+i];
  }

  l[n1] = INFTY;
  r[n2] = INFTY;

  i=0;
  j=0;

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

    if( l[i] <= r[j]) {
      a[k] = l[i];
      c[k] = lc[i];
      i++;
    }
    else {
      a[k] = r[j];
      c[k] = rc[j];
      j++;
    }

  }

  free(l);
  free(r);
  free(lc);
  free(rc);

}

void mergeSort( int* a, char* c, int left, int right) {

  int mid;

  if( left+1 < right) {
    mid = ( left + right)/2;
    mergeSort( a, c, left, mid);
    mergeSort( a, c, mid, right);
    merge( a, c, left, mid, right);
  }

}

main() {

  int n;
  int* a, * ma;
  char* c, * mc;
  int isStable;

  int i;

  scanf("%d", &n);

  a = (int*)malloc( sizeof( int ) * n );
  c = (char*)malloc( sizeof( char ) * n );

  //マージソート用配列
  ma = (int*) malloc( sizeof( int ) * n );
  mc = (char*)malloc( sizeof( char ) * n );

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

  quickSort( a, c, 0, n-1);
  mergeSort( ma, mc, 0, n);

  isStable = true;
  for( i=0; i<n; i++) {
    if(c[i] != mc[i]) {
      isStable = false;
      break;
    }
  }

  if( isStable == true) {
    printf("Stable\n");
  }else {
    printf("Not stable\n");
  }

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

  return 0;
}

Quick Sort

Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards 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

Quicksort(A, p, r)
1 if p < r
2 then q = Partition(A, p, r)
3 run Quicksort(A, p, q-1)
4 run Quicksort(A, q+1, r)

Here, A is an array which represents a deck of cards and comparison operations are performed based on the numbers.

Your program should also report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance).

Input

The first line contains an integer n, the number of cards.

n cards are given in the following lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space.

Output

In the first line, print the stability ("Stable" or "Not stable") of this output.

In the following lines, print the arranged cards in the same manner of that of the input.

Constraints

1 ≤ n ≤ 100,000

1 ≤ the number of a card ≤ 109

There are no identical card in the input

Sample Input 1

6
D 3
H 2
D 1
S 3
D 2
C 1

Sample Output 1

Not stable
D 1
C 1
D 2
H 2
D 3
S 3

Sample Input 2

2
S 1
H 1

Sample Output 2

Stable
S 1
H 1


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

void Quicksort(int, int);
int Partition(int, int);

typedef struct{
  int n;
  char c;
  int count;
}Card;

Card a[100000];

int main(void){
  int n,i,q,f=0;
  char y;

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

  Quicksort(1,n);

  for(i = 0; i < n; i++){
    if(a[i].n == a[i+1].n && a[i].count > a[i+1].count){
      f = 1;
      break;
    }
  }

  if(f == 0){
    printf("Stable\n");
  }else{
    printf("Not stable\n");
  }

  for(i = 1; i < n+1; i++){
    printf("%c %d\n",a[i].c,a[i].n);
  }
  return 0;
}
  void Quicksort(int p, int r){
  int q;
  if(p < r){
    q = Partition(p,r);
    Quicksort(p,q-1);
    Quicksort(q+1,r);
  }
}
int Partition(int p, int r){
  int i,j;
  Card x,tmp;

  x = a[r];
  i = p - 1;

  for(j = p; j <= r-1; j++){
    if(a[j].n <=  x.n){
      i =  i + 1;
      tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }
  }
  tmp = a[i+1];
  a[i+1] = a[r];
  a[r] = tmp;

  return i+1;
}


#include<stdio.h>
#define N 100000
#define M 2000000000
#define O 0
#define I 1
#define W 2
#define Z 10

struct Card{
  char s;
  int v;
};

struct Card L[N],R[N];

void merge(struct Card A[],int n,int left,int mid,int right){
  int i,j,k;
  int n1=mid-left;
  int n2=right-mid;
  for(i=O;i<n1;i++){
    L[i]=A[left+i];
  }
  for(i=O;i<n2;i++){
    R[i]=A[mid+i];
  }
  L[n1].v=R[n2].v=M;
  i=j=O;
  for(k=left;k<right;k++){
    if(L[i].v<=R[j].v){
      A[k]=L[i++];
    }
    else{
      A[k]=R[j++];
    }
  }
}

void m_sort(struct Card A[],int n,int left,int right){
  int mid;
  if(left+I<right){
    mid=(left+right)/W;
    m_sort(A,n,left,mid);
    m_sort(A,n,mid,right);
    merge(A,n,left,mid,right);
  }
}

int partition(struct Card A[],int n,int p,int r){
  int i,j;
  struct Card t,x;
  x=A[r];
  i=p-I;
  for(j=p;j<r;j++){
    if(A[j].v<=x.v){
      i++;
      t=A[i];
      A[i]=A[j];
      A[j]=t;
    }
  }
  t=A[i+I];
  A[i+I]=A[r];
  A[r]=t;
  return i+I;
}

void quickSort(struct Card A[],int n,int p,int r){
  int q;
  if(p<r){
    q=partition(A,n,p,r);
    quickSort(A,n,p,q-I);
    quickSort(A,n,q+I,r);
  }
}

int main(){
  int i,n,v;
  struct Card A[N],B[N];
  char S[Z];
  int stable=I;

  scanf("%d",&n);
  for(i=O;i<n;i++){
    scanf("%s %d",S,&v);
    A[i].s=B[i].s=S[O];
    A[i].v=B[i].v=v;
  }
  m_sort(A,n,O,n);
  quickSort(B,n,O,n-I);
  for(i=O;i<n;i++){
    if(A[i].s!=B[i].s){
      stable=O;
    }
  }

  if(stable==I){
    printf("Stable\n");
  }
  else{
    printf("Not stable\n");
  }
  for(i=O;i<n;i++){
    printf("%c %d\n",B[i].s,B[i].v);
  }
  return O;
}


#include<stdio.h>
#define MAX 100000
#define SENTINEL 2000000000

struct Card{
  char suit;
  int value;
};

struct Card L[MAX/2+2], R[MAX/2+2];

void merge(struct Card A[], 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] = A[left + i];
  for ( i = 0; i < n2; i++ ) R[i] = A[mid + i];
  L[n1].value = R[n2].value = SENTINEL;
  i = j = 0;
  for ( k = left; k < right; k++ ){
    if ( L[i].value <= R[j].value ){
      A[k] = L[i++];
    } else {
      A[k] = R[j++];
    }
  }
}

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

int partition(struct Card A[], int n, int p, int r){
  int i, j;
  struct Card t, x;
  x = A[r];
  i = p - 1;
  for ( j = p; j < r; j++ ){
    if ( A[j].value <= x.value ){
      i++;
      t = A[i]; A[i] = A[j]; A[j] = t;
    }
  }
  t = A[i+1]; A[i+1] = A[r]; A[r] = t;
  return i+1;
}

void quickSort(struct Card A[], int n, int p, int r){
  int q;
  if ( p < r ){
    q = partition(A, n, p, r);
    quickSort(A, n, p, q - 1);
    quickSort(A, n, q + 1, r);
  }
}

main(){
  int n, i, v;
  struct Card A[MAX], B[MAX];
  char S[10];
  int stable = 1;
  scanf("%d", &n);

  for ( i = 0; i < n; i++ ) {
    scanf("%s %d", S, &v);
    A[i].suit = B[i].suit = S[0];
    A[i].value = B[i].value = v;
  }

  mergeSort(A, n, 0, n);
  quickSort(B, n, 0, n-1);

  for ( i = 0; i < n; i++ ){
    if ( A[i].suit != B[i].suit ) stable = 0;
  }

  if ( stable == 1 ) printf("Stable\n");
  else printf("Not stable\n");
  for ( i = 0; i < n; i++ ) {
    printf("%c %d\n", B[i].suit, B[i].value);
  }
}


#include<stdio.h>
struct Node{
  int a,b,c;
};
struct Node N[10000];
int depth(int);
int sibling(int);
int n;
int D[10000],S[10000];
int main(){
  int i,j,k,l,m,q,r,s;
  scanf("%d",&n);
  for(i=0;i<n;i++){
    N[i].a=-1;
  }
  for(i=0;i<n;i++){
    scanf("%d %d %d",&q,&r,&s);
    N[q].b=r;
    N[q].c=s;
    if(r!=-1){
      N[r].a=q;
    }
    if(s!=-1){
      N[s].a=q;
    }
  }
  for(i=0;i<n;i++){
    D[i]=depth(i);
    S[i]=0;
  }
  for(i=0;i<n;i++){
    if(N[i].b==-1 && N[i].c==-1){
      S[i]=0;
      k=N[i].a;
      l=1;
      while(1){
        if(k==-1){
          break;
        }
        if(S[k]<l){
          S[k]=l;
        }
        l++;
        k=N[k].a;
      }
    }
  }
  for(i=0;i<n;i++){
    j=0;
    printf("node %d: ",i);
    printf("parent = %d, ",N[i].a);
    printf("sibling = %d, ",sibling(i));
    if(N[i].b!=-1 || N[i].c!=-1){
      j++;
    }
    printf("degree = %d, ",j);
    printf("depth = %d, ",D[i]);
    printf("height = %d, ",S[i]);
    if(N[i].a==-1){
      printf("root\n");
    }
    else if(N[i].b==-1 && N[i].c==-1){
      printf("leaf\n");
    }
    else{
      printf("internal node\n");
    }
    }
    return 0;
}

int depth(int r){
  int c=0;
  while(1){
    r=N[r].a;
    if(r==-1){
      break;
    }
    c++;
  }
  return c;
}

int sibling(int s){
  if(N[s].a==-1){
    return -1;
  }
  if(N[N[s].a].b!=s && N[N[s].a].b!=-1){
    return N[N[s].a].b;
  }
  if(N[N[s].a].c!=s && N[N[s].a].c!=-1){
    return N[N[s].a].c;
  }
  return -1;
}

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 1000
int main(){

  int n,id,k,m,i,j,dat[MAX][MAX];

  //入力

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

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

    printf("node %d: ",i);

    for (j = 0; ;j++){
      if(i == dat[i-j][j+1] && i > 0){
	printf("parent = %d", i-j);
      }
    }

  }

  return 0;
}


#include<stdio.h>

typedef struct node{

  int num;
  int depth;
  int parent;
  int br;
  int child;

}Node;
Node node[100001];
void nodegene( Node*);

//void putdepth( Node*);

int depth(int);

void nodegene( Node* nod){

  nod -> depth = 0;
  nod -> child = -1;
  nod -> br = -1;
  nod -> parent = -1;

}

int depth(int k){
  int dep = 0;
  for(dep = 0 ; node[k].parent != -1 ; dep++){
    k = node[k].parent;
  }
  return dep;

}
int main(){

  int i, j, m, n, l, nod, d, degree,br;

  Node c;
  scanf("%d",&m);

  for( i =0; i < m; i++)nodegene(&node[i]);

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

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

    for( j = 0; j < nod; j++){

      scanf("%d", &degree);

      if( node[n].child == -1){
	node[n].child = degree;
	node[degree].parent = n;
      }
      else if(node[n].child != -1){
	l = node[n].child;
	while( node[l].br != -1) l = node[l].br;

	node[l].br = degree;
	node[degree].parent = n;
      }
    }
  }

  //  for(i = 0; i < m; i ++)putdepth(&node[i]);

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

    printf("node %d: parent = %d, depth = %d, ", i, node[i].parent,depth(i));

    if(node[i].child == -1 && node[i].parent != -1)
      printf("leaf, ");
    else if(node[i].parent == -1)
      printf("root, " );
    else if(node[i].child != -1 && node[i].parent != -1)
      printf("internal node, " );

    printf("[");

    if(node[i].child != -1){

      printf("%d",node[i].child);

      br = node[i].child;

      while(1){
	if(node[br].br == -1)
	  break;
	printf(", %d",node[br].br);
	br = node[br].br;
      }
    }

    printf("]\n");
  }
  return 0;
}


#include<stdio.h>
#include<stdlib.h>
typedef struct{
  int parent;
  int left;
  int right;
}Node;

int main(){
  int n,k,id,h,r,depth,p,i,j;
  Node *T;

  scanf("%d", &n);

  T=malloc(sizeof(Node)*n);

  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 %d", &id, &k);
    for(j=0;j<k;j++){
      scanf("%d",&h);
      T[h].parent=id;

      if(j==0) T[id].left=h;
      else if(j>0) T[r].right = h;
      r=h;
    }
  }

  for(j=0;j<n;j++){
    depth=0;
    p=T[j].parent;

    while(p!=-1){
      p=T[p].parent;
      depth++;
    }

    if(depth==0){
      printf("node %d: parent = -1, depth = 0, root, [", j);
    }

    else if(T[j].left == -1){
      printf("node %d: parent = %d, depth = %d, leaf, [", j, T[j].parent, depth);
    }
    else{
      printf("node %d: parent = %d, depth = %d, internal node, [", j, T[j].parent, depth);
    }

    p = T[j].left;
    if(p != -1) printf("%d", p);

    while(p != -1){
      p = T[p].right;
      if(p != -1) printf(", %d", p);
    }
    printf("]\n");
  }

  return 0;
}


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

int main(){
  int i,j,n,id,l,s=0,t;
  int **node,*d,*p,*k;
  char *r[12];

  scanf("%d",&n);

  node = (int **)malloc(sizeof(int *) * n);
  d = (int *)malloc(sizeof(int) * n);
  p = (int *)malloc(sizeof(int) * n);
  k = (int *)malloc(sizeof(int) * n);

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

    scanf("%d",&id);
    scanf("%d",&k[id]);

    node[id] = (int *)malloc(sizeof(int) * k[id]);

    for(j = 0 ; j < k[id] ; j++){
      scanf("%d",&node[id][j]);
    }
  }

  for(i = 0 ; i < n ; i++){
    s = 0;
    if(k[i] > 0){
      for(j = 0 ; j < n ; j++){

	if(s == 1)break;

	for(l = 0 ; l < k[j] ; l++){
	  if(i == node[j][l]){
	    p[i] = j;
	    r[i] = "internal node, ";
	    s = 1;
	    break;
	  }
	}

	if(s == 0){
	  p[i] = -1;
	  r[i] = "root, ";
	}
      }
    }

    else if(k[i] == 0){
      for(j = 0 ; j < n ; j++){
	for(l = 0 ; l < k[j] ; l++){
	  if(i == node[j][l]){
	    p[i] = j;
	    r[i] = "leaf, ";
	    break;
	  }
	}
      }
    }

  }

  for(i = 0 ; i < n ; i++){
    s = p[i];
    d[i] = 0;
    while(s != -1){
      d[i]++;
      t = p[s];
      s = t;
    }
  }

  for(i = 0 ; i < n ; i++){
    printf("node %d: ",i);
    printf("parent = %d, ",p[i]);
    printf("depth = %d, ",d[i]);
    printf("%s",r[i]);

    printf("[");

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

  return 0;
}


#include<stdio.h>
#define N 100000
#define NIL -1

typedef struct{
  int parent;
  int left;
  int right;
  int k;
}Node;

Node node[N];

int depth(int);

int main(){
  int i, j, id, sub, m, n, child;
  scanf("%d", &n);
  for(i = 0;i < n;i++){
    node[i].left = node[i].parent = NIL;
  }
  for(i = 0;i < n;i++){
    scanf("%d%d", &id, &m);
    node[id].k = m;
    sub = id;
    for(j = 0;j < m;j++){
      scanf("%d", &child);
      if(j == 0){
        node[sub].left = child;
        node[node[sub].left].parent = id;
        sub = child;
      }
      else{
        node[sub].right = child;
        node[node[sub].right].parent = id;
        sub = child;
      }
    }
  }
  for(i = 0;i < n;i++){
    printf("node %d: parent = %d, depth = %d, ", i, node[i].pa\
rent, depth(i));
    if(node[i].left != NIL){
      if(node[i].parent != NIL){
        printf("internal node, [");
      }
      else{
        printf("root, [");
      }
      for(j = 0;j < node[i].k-1;j++){
        if(j == 0){
          sub = node[i].left;
          printf("%d, ", node[i].left);
        }
        else{
          printf("%d, ", node[sub].right);
          sub = node[sub].right;
        }
      }
      if(node[i].k == 1){
        printf("%d]\n", node[i].left);
      }
      else{
        printf("%d]\n", node[sub].right);
      }
    }
    else{
      if(node[i].parent == NIL){
        printf("root, []\n");
      }
      else{
        printf("leaf, []\n");
      }
    }
  }
  return 0;
}

int depth(int id){
  int dep = 0;
  while(1){
    if(node[id].parent == NIL){
      return dep;
    }
    else{
      dep++;
      id = node[id].parent;
    }
  }
}


#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].r != NIL) calcDepth(T[u].r,p);
 if(T[u].l != NIL) calcDepth(T[u].l,p+1);
}

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>

#define MAX 100000
#define NIL -1

struct Type{
  int p, l, r;
};
struct Type A[MAX];

int n,D[MAX];

int getDegree(int u){
  if(A[u].l!=NIL && A[u].r!=NIL) return 2;
  else if(A[u].l==NIL && A[u].r==NIL) return 0;
  else return 1;
}

int getDepth(int u){
  int d=0;
  while(A[u].p!=NIL){
    u=A[u].p;
    d++;
  }
  return d;
}

int getHeight(int u,int count){
  int height1=0,height2=0;
  count++;
  if(A[u].l!=NIL){
    height1=getHeight(A[u].l,count);
  }
  if(A[u].r!=NIL){
    height2=getHeight(A[u].r,count);
  }
  if(A[u].l==NIL && A[u].r==NIL){
    return count;
  }
  if(height1<height2)return height2;
  else return height1;
}

int getSibling(int u){
  int p;
  if(A[u].p==NIL)return -1;
  p=A[u].p;
  if(A[p].l==u)return A[p].r;
  if(A[p].r==u)return A[p].l;
}

void print(int u){
  int i;
  printf("node %d: parent = %d, sibling = %d, degree = %d, depth = %d, height = %d, ",u,A[u].p,getSibling(u),getDegree(u),D[u],getHeight(u,-1));
  if(A[u].p==NIL)printf("root\n");
  else if(A[u].l==NIL && A[u].r==NIL) printf("leaf\n");
  else if(A[u].l!=NIL || A[u].r!=NIL )printf("internal node\n");
}

main(){
  int i, j,v,l,r;
  scanf("%d", &n);
  for(i=0;i<n;i++) {
    A[i].p=NIL;
    A[i].l=NIL;
    A[i].r=NIL;
  }
  for(i=0;i<n;i++){
    scanf("%d %d %d",&v,&l,&r);
    A[v].p=l;
    A[v].r=r;
    A[l].p=v;
    A[r].p=v;
  }
  for(i=0;i<n;i++){
    D[i]=getDepth(i);
  }
  for(i=0;i<n;i++) print(i);
  return 0;
}

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>

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

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

struct Node *root, *NIL;

int main(){
  int n=0;
  int i=0;
  int number=0;
  char word[6];
  char space;
  int print_flag=0;
  scanf("%d", &n);
  for(i=0;i<n;i++){
    scanf("%s",word);

    if(word[0]=='i')
      {
	scanf("%d%c",&number,&space);
	insert(number);
      }

    else if(word[0]=='p')
      {
	print_flag=1;
      }

    if(print_flag==1){
      inorder(root);
      printf("\n");
      preorder(root);
      printf("\n");
      print_flag=0;
    }
  }

    return 0;
}

void insert(int number){
  struct Node *y=NIL;
  struct Node *x=root;
  struct Node *z;

  z=(struct Node *)malloc(sizeof(struct Node));
  z->key=number;
  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;
    }
  }
}

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

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

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.


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

#define NIL NULL

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

typedef struct node * Node;

Node root;

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

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

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

}
void preorder(Node x){

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

int main(){

  int n,i,x;
  char com[20];
  root = NIL;
  scanf("%d",&n);

for ( i = 0; i < n; i++ ){
    scanf("%s", com);

    if ( com[0] == 'i' ){
      scanf("%d", &x);
      insert(x);
    } else if ( com[0] == 'p' ){
      inorder(root);
      printf("\n");
      preorder(root);
      printf("\n");
    }
 }
 return 0;
}


#include <stdio.h>
#include <stdlib.h>
typedef struct{
    int k,l,r;
}Node;
void insert(int, int);
void inParse(int);
void preParse(int);
Node T[500001];
int main(void)
{
    char s[8];
    int m;
    int num,count=0;
    int i;

    scanf("%d", &m);
    for(i=0; i<m; i++){
        scanf("%s", &s);
        if(s[0]=='i'){
          scanf("%d", &num);
          insert(count, num);
          count++;
        }
        if(s[0]=='p'){
          if(count>0) inParse(0);
            printf("\n");
            if(count>0) preParse(0);
            printf("\n");
        }
    }
    return 0;
}

void inParse(int p){
    if(T[p].l>=0) inParse( T[p].l);
    printf(" %d", T[p].k);
    if(T[p].r>=0) inParse( T[p].r);
}

void preParse(int p){
    printf(" %d", T[p].k);
    if(T[p].l>=0) preParse(T[p].l);
    if(T[p].r>=0) preParse(T[p].r);
}

void insert(int count, int z){
    int x=0, y;
    if(count<1) x=-1;

    T[count].k = z;
    T[count].l = -1;
    T[count].r = -1;

    while(x>=0){
        y = x;
        if(z < T[x].k)x = T[x].l;
        else x = T[x].r;
    }
    if(count<1){}
    else if(z < T[y].k)T[y].l = count;
    else T[y].r = count;
}


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

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){
    return;
  }
  inorder(u->left);
  printf(" %d",u->key);
  inorder(u->right);

}
void preorder(Node u){
  if(u==NIL){
    return;
  }
  printf(" %d",u->key);
  preorder(u->left);
  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] == 'i' ){
      scanf("%d", &x);
      insert(x);
    } else{
      inorder(root);
      printf("\n");
      preorder(root);
      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){
}
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);
}
Node treeSuccessor(Node x){
}
void treeDelete(Node z){
  Node y; // node to be deleted
  Node x; // child of y
}
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){
  if(u!=NIL){
    printf(" %d",u->key);
    preorder(u->left);
    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");

    } else 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'){
      printf("in delete\n");
      scanf("%d",&x);
      //treeDelete(treeSearch(root,x));
    }
  }
  return 0;
}

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>

  #define MAX 2000000

  int H,A[MAX+1];

  void maxHeapify(int i){
  int l,r,largest,C;
  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;

  if(largest != i ){
   C = A[i];
   A[i] = A[largest];
   A[largest] = C;
   maxHeapify(largest);
  }
}

  int main(){
  int i;
  scanf("%d",&H);
  for(i=1; i<=H; i++)scanf("%d",&A[i]);
  for(i=H/2; i>=1; i--)maxHeapify(i);
  for(i=1; i<=H; 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.