#include<stdio.h>

void output(int ph,int pm)
{
if(ph < 10)
printf("0%d:",ph);
else
printf("%d:",ph);
if(pm < 10)
printf("0%d\n",pm);
else
printf("%d\n",pm);

}
int main()
{
int n,hh,mm;
int ph,pm;
scanf("%d",&n);
scanf("%d:%d",&hh,&mm);
if(n == 12)
{
if(hh >= 1 && hh <= 12)
ph = hh;
else
{
//if(h/10 == 1)

//ph = hh % 10;
if(hh == 0)
ph = 1;

else if(hh % 10 == 0 )
ph =  10;
else
ph = hh % 10;
//if(h/10 != 1)

}
if(mm >= 0 && mm <= 59)
pm = mm;
else
pm = mm % 10;
}
else if(n == 24)
{
if(hh >= 0 && hh <= 23)
ph = hh;
else
{
ph = hh % 10;
}
if(mm >= 0 && mm <= 59)
pm = mm;
else
pm = mm % 10;
}

output(ph,pm);
}

You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.


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

int e[111][111],f[111];
int ans;
main(){
    int i,j,k;
    int n,m,a,b,c,count;
    scanf("%d%d",&n,&m);
    for(i=0;i<m;i++){
        scanf("%d%d",&a,&b);
        e[a][b]=e[b][a]=1;
    }
    c=1;
    while(c){
        c=0;
        memset(f,0,sizeof(f));
        for(i=1;i<=n;i++){
            count=0;
            for(j=1;j<=n;j++) count+=e[i][j];
            if(count==1){
                c=1;
                f[i]=1;
            }
        }
        ans+=c;
        for(i=1;i<=n;i++){
            if(f[i]==1){
                for(j=1;j<=n;j++) e[i][j]=e[j][i]=0;
            }
        }
    }

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

Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.


In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.


#include<stdio.h>
#include<string.h>
int main()
{
	char s[1001];
	int i,k,count,j,freq[1001],count1;
	 scanf("%s",&s);
	 scanf("%d",&k);

	if(strlen(s) <k)
	printf("impossible");
	else
    {for(i=0;i<strlen(s);i++)
        freq[i]=-1;

     for(i=0; i<strlen(s); i++)
    {
        count = 1;
        for(j=i+1; j<strlen(s); j++)
        {
            if(s[i]==s[j])
            {
                count++;
                freq[j] = 0;
            }
        }

        if(freq[i] != 0)
        {
            freq[i] = count;
        }
    }

    int d,t;
        for(i=0;i<strlen(s);i++)
        {

             d = i;
        while ( d > 0 && freq[d] < freq[d-1]) {
                        t= freq[d];
                    freq[d]= freq[d-1];
                    freq[d-1] = t;
                d--;
                }

        }
        int size,freq2[1001],n=0;
        //size = sizeof(freq)/sizeof(int);
        for(i=0;i<strlen(s);i++)
            if(freq[i]!=0)
        {
            freq2[n]= freq[i];
            n++;

        }

        if( n<k)
           printf("%d",k-n);
        else
            printf("0");

    }
}

#include<stdio.h>
#include<string.h>
int main()
{
    char str[1005];
    int chr[26],n,i,len,coun=0,ans,an;
    for(i=0;i<36;i++) chr[i]=0;
    scanf("%s%d",str,&n);
    len=strlen(str);
    if(len<n) printf("impossible\n");
    else
    {
        for(i=0;i<len;i++)
        {
            an=(str[i]-'a');
            chr[an]++;
        }
        for(i=0;i<26;i++)
        {
            if(chr[i]>0) coun++;
        }
        if(coun>=n)  ans=0;
        else if(coun<n)
        {
            ans=n-coun;
        }
        printf("%d\n",ans);
    }
    return 0;
}

Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

[{'input': 'yandex\n6\n', 'output': ['0\n']}, {'input': 'yahoo\n5\n', 'output': ['1\n']}, {'input': 'google\n7\n', 'output': ['impossible\n']}, {'input': 'a\n1\n', 'output': ['0\n']}, {'input': 'z\n2\n', 'output': ['impossible\n']}, {'input': 'fwgfrwgkuwghfiruhewgirueguhergiqrbvgrgf\n26\n', 'output': ['14\n']}, {'input': 'nfevghreuoghrueighoqghbnebvnejbvnbgneluqe\n26\n', 'output': ['12\n']}, {'input': 'a\n3\n', 'output': ['impossible\n']}, {'input': 'smaxpqplaqqbxuqxalqmbmmgubbpspxhawbxsuqhhegpmmpebqmqpbbeplwaepxmsahuepuhuhwxeqmmlgqubuaxehwuwasgxpqmugbmuawuhwqlswllssueglbxepbmwgs\n1\n', 'output': ['0\n']}, {'input': 'cuguccgcugcugucgggggcgcgucgucugcuuuccccuugccg\n4\n', 'output': ['1\n']}, {'input': 'fcfccfcfccfcfcffcffffffcfccfccfcffccccfcffffccfccfcffcfcccccffcfffcccffcfccfffffcccfccffffffccfccccf\n20\n', 'output': ['18\n']}, {'input': 'swmkwaruyv\n5\n', 'output': ['0\n']}, {'input': 'tnbqpsuhkczmejirvyfdolxwga\n22\n', 'output': ['0\n']}, {'input': 'abcde\n3\n', 'output': ['0\n']}, {'input': 'abb\n1\n', 'output': ['0\n']}, {'input': 'aaaa\n1\n', 'output': ['0\n']}, {'input': 'abcde\n2\n', 'output': ['0\n']}, {'input': 'yandex\n4\n', 'output': ['0\n']}, {'input': 'aaabbbccc\n1\n', 'output': ['0\n']}, {'input': 'abcd\n2\n', 'output': ['0\n']}, {'input': 'asdfgh\n2\n', 'output': ['0\n']}, {'input': 'aab\n1\n', 'output': ['0\n']}, {'input': 'mynameissako\n5\n', 'output': ['0\n']}, {'input': 'abcde\n1\n', 'output': ['0\n']}, {'input': 'abcd\n3\n', 'output': ['0\n']}, {'input': 'abcdef\n2\n', 'output': ['0\n']}, {'input': 'abcdefg\n4\n', 'output': ['0\n']}, {'input': 'abc\n1\n', 'output': ['0\n']}, {'input': 'asdafjsgljdllgjdgkl\n5\n', 'output': ['0\n']}, {'input': 'yaay\n3\n', 'output': ['1\n']}, {'input': 'yaay\n4\n', 'output': ['2\n']}, {'input': 'zzzzzz\n2\n', 'output': ['1\n']}]


main(i,l){
  char s[100001],t[100001],x[101],y[101],*p,*q;
  scanf("%s%s%s",s,x,y);
  {for(i=0,l=strlen(s);i<l;i++)t[i]=s[l-i-1];}
  p=strstr(s,x);if(p)p=strstr(p+strlen(x),y);
  q=strstr(t,x);if(q)q=strstr(q+strlen(x),y);
  if(p){
    if(q)puts("both");
    else puts("forward");
  }else{
    if(q)puts("backward");
    else puts("fantasy");
  }
  return 0;
}

#include <stdio.h>
#include <string.h>
void fan(char s[])
{
	int len = strlen(s)-1;
	char c;
	int i = 0;
	for (i = 0; i < len - i; i++)
	{
		c = s[i];
		s[i] = s[len- i];
		s[len - i] = c;
	}
}
char s[100001];
char s1[100000];
char s2[100000];
int main()
{
	char *p1, *p2;
	int f = 0, b = 0;
	int f1 = 0, b1 = 0;
	scanf("%s%s%s",s,s1,s2);
    int len1 = strlen(s1);
    int len2 = strlen(s2);
	p1 = strstr(s, s1);
	if (p1 != NULL)
	{
		p2 = strstr(p1+len1, s2);
		if (p2 != NULL)
			f = 1;
		p2 = strstr(p1 , s2);
		if (p2 != NULL)
			f1 = 1;
	}
	fan(s1);
	fan(s2);
	p2 = strstr(s, s2);
	if (p2 != NULL)
	{
		p1 = strstr(p2+len2, s1);
		if (p1 != NULL)
			b = 1;
		p1 = strstr(p2 , s1);
		if (p1 != NULL)
			b1 = 1;
	}

	if (f*b)
	{
		printf("both\n");
		return 0;
	}
	else if (f == 1)
	{
		printf("forward\n");
		return 0;
	}
	else if (b == 1)
	{
		printf("backward\n");
		return 0;
	}
	else if((f==0 && f1!=0)||(b==0&&b1!=0)||(f == 0 && f1==0 && b==0 && b1==0))
		printf("fantasy\n");
	return 0;
}

Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

[{'input': 'atob\na\nb\n', 'output': ['forward\n']}, {'input': 'aaacaaa\naca\naa\n', 'output': ['both\n']}, {'input': 'aaa\naa\naa\n', 'output': ['fantasy\n']}, {'input': 'astalavista\nastla\nlavista\n', 'output': ['fantasy\n']}, {'input': 'abacabadabacaba\nabacaba\nabacaba\n', 'output': ['both\n']}, {'input': 'a\na\na\n', 'output': ['fantasy\n']}, {'input': 'ab\nb\na\n', 'output': ['backward\n']}, {'input': 'aaa\naaaa\naaaa\n', 'output': ['fantasy\n']}, {'input': 'bbabbbbababbaabaabaa\nabb\nbaab\n', 'output': ['forward\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\nbbbb\nbbbbb\n', 'output': ['both\n']}, {'input': 'babaabababaaaababaabababaabababababababbababbbabbaabababaababbaabbababaababaaabababaabbaababaaababaa\nabaabababaa\nabaabbaa\n', 'output': ['forward\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\nbbbb\nbbbbb\n', 'output': ['both\n']}, {'input': 'aababaaababaabbaabababaaababaabababbaabbabaabababaabbabbbababbababababababaabababaababaaaabababaabab\nabaabababaa\nabaabbaa\n', 'output': ['backward\n']}, {'input': 'aaaa\naaa\naa\n', 'output': ['fantasy\n']}, {'input': 'zzzz\nzz\nzzz\n', 'output': ['fantasy\n']}, {'input': 'zzzz\nzzzz\nzzzz\n', 'output': ['fantasy\n']}, {'input': 'zzzz\nzz\nzz\n', 'output': ['both\n']}, {'input': 'aabaa\naab\nbaa\n', 'output': ['fantasy\n']}, {'input': 'aabaab\naba\nab\n', 'output': ['forward\n']}, {'input': 'aab\nb\naa\n', 'output': ['backward\n']}, {'input': 'abacaba\naca\nba\n', 'output': ['both\n']}]


#include <stdio.h>
#include <stdlib.h>
typedef struct {int num; int ab;} boy;
boy arr[110000], k;
int n,t,j,i;
int cmp(const void* el1, const void* el2){ boy a=(*(boy*)el1); boy b=(*(boy*)el2);
	return (a.ab==b.ab)?0:((a.ab>b.ab)?1:-1);
}

int main(){
 scanf("%d", &n);
 for(i=0; i<n; i++){
	 scanf("%d", &arr[i].ab);
 arr[i].num=i+1;
 } qsort(arr, n, sizeof(boy), &cmp);
 printf("%d\n", (n&1)+n/2);
 for(i=0; i<n; i+=2){
  printf("%d ", arr[i].num);
 }

putchar('\n');
 printf("%d\n", n/2);
 for(i=1; i<n; i+=2){
  printf("%d ", arr[i].num);
 }
 return 0;
}

Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled:  Each boy plays for exactly one team (x+y=n).  The sizes of teams differ in no more than one (|x-y|≤1).  The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.


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

#define MAX(x,y) (((x)>(y))?(x):(y))
#define MIN(x,y) (((x)<(y))?(x):(y))
int main(void){
  int n,i,ans1,ans2,ans3=1010;
  int *array;
  scanf("%d",&n);
  array=(int *)calloc(n,sizeof(int));
  for(i=0;i<n;i++) scanf("%d",array+i);
  ans1=*array;
  ans2=*(array+n-1);
  for(i=0;i<n-1;i++){
    if(ans3>MAX(*(array+i),*(array+i+1))){
      ans3=MAX(*(array+i),*(array+i+1));
    }
  }

  printf("%d\n",MIN(MIN(ans1,ans2),ans3));

  free(array);
  return 0;
}

In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i<n-1), you can reach the tiles number i+1 or the tile number i+2 from it (if you stand on the tile number n-1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai+1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.


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

int n, m, a[100];
bool match[100][100];
int main() {
    int i, j, k, mn=-1, v;
    scanf("%d%d", &n, &m);
    for(i=0; i<n; i++) scanf("%d", &a[i]);
    memset(match, false, sizeof(match));
    for(i=0; i<m; i++){
        scanf("%d%d", &j, &k); j--; k--;
        match[j][k] = match[k][j] = true;
    }
    for(i=0; i<n; i++)
        for(j=0; j<n; j++) {
            if (!match[i][j]) continue;
            for(k=0; k<n; k++){
                if (!match[i][k] || !match[j][k]) continue;
                v = a[i]+a[j]+a[k];
                if (mn==-1 || v < mn) mn = v;
            }
        }
    printf("%d\n", mn);
    return 0;
}

A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.


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

int main()
{
    int i,  n, current = 0, maxx = 0,  prev = 0, ar[1000];
    char sign;
    int ins;
    static int reg[1000009];

    for (i = 1; i < 1000009; i++ )
    {
    	reg[i] = 0;
    }

    scanf("%d", &n);

    for (i = 1; i <= n; i++)
    {
    	getchar();
    	scanf("%c", &sign);
        scanf("%d", &ar[i]);
        if (sign == '-')
        {
        	ar[i] *= -1;
        }

    }

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

    for (i = 1; i <= n; i++)
    {
//        scanf("%d", &ins);

        ins = ar[i];

        if (ins > 0)
        {
            current ++;
            reg[ins]++;
        }

        if (ins < 0)
        {
        	ins = -ins;

            if ( reg[ ins ] != 0 )
            {
                current--;
                reg[ ins ]--;
            }

            else //if ( reg[ -ins ] == 0 )
            {
                maxx++;
            }
        }

        if (current > maxx)
        {
            maxx = current;
        }

//       printf("\n current = %d \t max = %d \n", current, maxx);

    }

    printf("%d", maxx);

    return 0;
}

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>

#define PI 3.141592653589793
#define max(a,b) (a < b) ? (b) : (a)
#define min(a,b) (a > b) ? (b) : (a)
#define FOR(i,a,b) for(i = a ; i <= b ; i++)
#define ROF(i,a,b) for(i = a ; i >= b ; i--)
#define RAD(x) ((x)*PI)/180
#define y1 y_1
#define ll long long
#define endl printf("\n")
#define MAX 1000005

int i, j, n, a, cvp, mx, h[MAX];
char b;

int main () {
	scanf("%d",&n);
	FOR(i, 1, n){
		cvp = 0;
		scanf(" %c %d",&b,&a);
		if(b == '+')
			h[a]++;
		else{
			if(!h[a])
				mx++;
			else
				h[a]--;
		}
		FOR(j, 1, MAX - 3)
			cvp += h[j] != 0;
		mx = max(cvp, mx);
	}
	printf("%d\n",mx);
	return 0;
}

Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 10^6. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.


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

int main(){
   int t, m, mem[100] = {0};
   scanf("%d%d", &t, &m);

   int i, lastid = 0, alive[102] = {0}, start[102], lens[102], usedlen = 0;
   for(i = 0; i < t; ++i){
      char cmd[100];
      scanf("%s", cmd);

      if(cmd[0] == 'a'){
         int len;
         scanf("%d", &len);

         if(len <= m-usedlen){
            int j = 0;
            while(j < m){
               while(j < m && mem[j]) ++j;
               if(j >= m) break;

               int k = j;
               while(k < m && mem[k] == 0) ++k;

               if(k-j >= len){
                  lastid++;
                  alive[lastid] = 1;
                  start[lastid] = j;
                  lens[lastid] = len;
                  usedlen += len;
                  int p;
                  for(p = j; p < j+len; ++p) mem[p] = lastid;
                  printf("%d\n", lastid);
                  break;
               }else j = k;
            }
            if(j >= m) puts("NULL");
         }else puts("NULL");
      }else if(cmd[0] == 'e'){
         int eid;
         scanf("%d", &eid);

         if(eid >= 1 && eid <= lastid && alive[eid] == 1){
            alive[eid] = 0;
            usedlen -= lens[eid];

            int j;
            for(j = start[eid]; j < start[eid]+lens[eid]; j++) mem[j] = 0;
         }else puts("ILLEGAL_ERASE_ARGUMENT");
      }else{
         int j;
         for(j = 0; j < m; ++j){
            if(mem[j]){
               int k;
               for(k = j-1; k >= 0 && mem[k] == 0; k--){
                  mem[k] = mem[k+1];
                  mem[k+1] = 0;
               }
            }
         }

         for(j = m-1; j >= 0; --j) if(mem[j]) start[ mem[j] ] = j;
      }
      /*
      int kkk;
      for(kkk = 0; kkk < m; ++kkk) printf("%d", mem[kkk]);
      putchar('\n');*/
   }

   return 0;
}

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int M, counter;
int memory[102];
int map[102][3];

void initializeMem(int size){
  int ii;
  counter = 0;
  for(ii=1; ii<=101; ii++){
    memory[ii]=0;
    map[ii][0]=-1;
    map[ii][1]=-1;
  }
}

void printMem(){
	printf("\n[");
	int i;
	for(i=1;i<=M;i++){
		printf("%d ",memory[i]);
	}
	printf("]\n");
	printf("\n[");
	for(i=1;i<=100;i++){
		if(map[i][0]!=-1)
			printf("[%d|%d %d] ",i, map[i][0],map[i][1]);
	}
	printf("]\n");
}

void alokasi(int size){
//	printf("s = %d\n",size);
	int ii,jj,status,iii;
	for(ii=1; ii<=M; ii++){
		jj=ii;
		status = 0;
		while((jj-ii<size) && memory[jj]==0 && jj<=M){
//			printf("masuk\n");
			jj++;
			status = 1;
		}
//		printf("status %d\n",status);
		if(status == 1){
			if(jj-ii==size && jj<=M+1){
				counter++;
				map[counter][0]=ii;
				map[counter][1]=size;
				for(iii=ii;iii<jj;iii++) memory[iii]=1;
				printf("%d\n",counter);
				return;
			}
		}else{

		}
	}
	printf("NULL\n");
}

void hapus(int idx){
	if(idx<1 || idx >100 || map[idx][0]==-1){
		printf("ILLEGAL_ERASE_ARGUMENT\n");
	}else{
		int ii, batas = map[idx][0] + map[idx][1];
		for(ii=map[idx][0]; ii<batas; ii++) memory[ii]=0;
		map[idx][0]=-1;
		map[idx][1]=-1;
	}
}

void changeMap(int minIdx, int moves){
	int i;
	for(i=1;i<=100;i++){
		if(map[i][0]>=minIdx){
			map[i][0]-=moves;
		}
	}
}

void fragment(){
	int i, j, k, count=0, batas;
	for(i=1; i<=M; i++){
		if(memory[i]==0){
			j=i;
			while(j<=M && memory[j]==0) j++;
			if(j<=M){
				batas = j-i;
				changeMap(j, batas);
				for(k=i; j<=M; k++){
					memory[k] = memory[j];
					memory[j] = 0;
					j++;
				}
			}
		}
	}
}

int main(){
  int tC, value;
  char inp[50];
  scanf("%d %d",&tC, &M);
  getchar();
  initializeMem(M);

  while(tC--){
    gets(inp);
    char  *token = strtok(inp, " ");
    while(token) {
      if(strcmp(token, "alloc")==0) {
//      	printMem();
        token = strtok(NULL, " ");
		value = atoi(token);
        alokasi(value);
//        printMem();
      }
      else if(strcmp(token, "erase")==0) {
//      	printMem();
        token = strtok(NULL, " ");
        value = atoi(token);
        hapus(value);
//        printMem();
      }
      else if(strcmp(token, "defragment")==0) {
//      	printMem();
      	fragment();
//      	printMem();
	  }
      token = strtok(NULL, " ");
    }
  }
}

There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:   alloc n — to allocate n bytes of the memory and return the allocated block's identifier x;  erase x — to erase the block with the identifier x;  defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.

[{'input': '6 10\nalloc 5\nalloc 3\nerase 1\nalloc 6\ndefragment\nalloc 6\n', 'output': ['1\n2\nNULL\n3\n']}, {'input': '6 1\ndefragment\nalloc 10\nalloc 1\nerase -1\nerase 1\nerase 1\n', 'output': ['NULL\n1\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '14 100\nalloc 99\nalloc 1\nalloc 1\nerase 2\nalloc 1\nerase 4\nerase 1\nalloc 100\nalloc 1\nalloc 99\ndefragment\nerase 4\nalloc 100\nalloc 99\n', 'output': ['1\n2\nNULL\n3\nILLEGAL_ERASE_ARGUMENT\nNULL\n4\nNULL\nNULL\nNULL\n']}, {'input': '26 25\ndefragment\nerase 1\nerase -1560200883\nalloc 44\ndefragment\nalloc 75\nalloc 22\ndefragment\nerase 4\ndefragment\nalloc 57\nalloc 53\nerase 4\nerase -1639632026\nerase -2121605039\nerase 3\nalloc 51\nalloc 65\ndefragment\nerase 2\nerase 4\nalloc 52\nerase 3\ndefragment\nerase -1842529282\nerase 3\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\n1\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '22 9\nerase 1\nalloc 6\nalloc 65\nerase 1\nalloc 87\nerase -1638927047\nalloc 5\nerase 2\nalloc 70\ndefragment\nalloc 20\nalloc 48\nerase -69401977\nalloc 20\ndefragment\nerase 7\ndefragment\nerase 9\nerase 7\nerase 4\ndefragment\nalloc 66\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\n1\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\n2\nNULL\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\n']}, {'input': '12 40\nerase 1\nalloc 21\nalloc 5\nalloc 7\ndefragment\ndefragment\nerase 2\nalloc 83\nerase 4\ndefragment\nalloc 59\ndefragment\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\n1\n2\n3\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\n']}, {'input': '38 18\nalloc 72\nerase 2\nalloc 50\ndefragment\nerase 3\ndefragment\nalloc 43\nalloc 41\ndefragment\ndefragment\nalloc 26\nalloc 46\nalloc 16\nalloc 15\ndefragment\ndefragment\nalloc 95\nerase 7\nerase 7\nerase 5\nerase 2\nerase 9\nerase 7\nalloc 43\ndefragment\nerase 7\ndefragment\nalloc 48\nalloc 77\nerase 10\nerase 11\nalloc 16\nalloc 84\nerase 1\ndefragment\nalloc 86\ndefragment\nerase 13\n', 'output': ['NULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nNULL\nNULL\n1\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '37 74\nalloc 11\ndefragment\nerase 1\ndefragment\nerase 2\ndefragment\nalloc 90\nerase 3\nerase 2\nerase 3\nerase 1\nerase 1\nalloc 38\nalloc 19\nerase 1\nerase 3\ndefragment\nalloc 93\nerase 5\nerase 4\nalloc 66\nalloc 71\nerase 5\ndefragment\ndefragment\ndefragment\ndefragment\nerase 7\nalloc 47\nerase -95616683\nerase 2\nalloc 28\nalloc 32\nerase 11\nalloc 50\ndefragment\ndefragment\n', 'output': ['1\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n2\n3\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\n4\n5\nILLEGAL_ERASE_ARGUMENT\nNULL\n']}, {'input': '16 49\nerase -751005193\ndefragment\nalloc 37\nalloc 82\nerase 3\nerase 1\nalloc 80\nalloc 51\ndefragment\nalloc 74\nerase 1\nalloc 91\ndefragment\ndefragment\nalloc 98\ndefragment\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\n1\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\n']}, {'input': '42 98\ndefragment\ndefragment\ndefragment\ndefragment\ndefragment\nalloc 5\nalloc 66\ndefragment\nerase 3\nalloc 53\ndefragment\nerase 4\nerase 2\nalloc 70\nerase 3\ndefragment\ndefragment\nerase 2\nerase 3\nerase -1327931832\nalloc 93\nalloc 64\nerase 7\nerase 6\nerase 3\nalloc 61\nalloc 12\nalloc 65\nerase 2\nalloc 46\nerase 11\nerase 9\nerase 9\nerase 6\nalloc 2\nalloc 78\ndefragment\nerase 13\nerase 6\nerase 10\nalloc 53\nalloc 46\n', 'output': ['1\n2\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\n3\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n4\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\n']}, {'input': '19 46\nalloc 21\nerase 2\nerase 1\ndefragment\nalloc 4\ndefragment\ndefragment\nalloc 40\nerase 1\ndefragment\ndefragment\nalloc 68\nerase -388966015\nalloc 85\nalloc 53\nerase 4\ndefragment\nalloc 49\nalloc 88\n', 'output': ['1\nILLEGAL_ERASE_ARGUMENT\n2\n3\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\n']}, {'input': '44 46\nalloc 28\nalloc 36\ndefragment\nerase -937404236\nalloc 71\ndefragment\nalloc 81\nalloc 51\nerase 3\ndefragment\nalloc 48\nerase 1\ndefragment\nalloc 36\ndefragment\ndefragment\nerase 1\ndefragment\ndefragment\nerase -1173350787\nalloc 94\nerase 5\ndefragment\nerase 9\nalloc 98\nerase 7\ndefragment\nerase 5\nerase 1\ndefragment\nerase 2\ndefragment\nerase 4\ndefragment\nerase 9\nalloc 8\ndefragment\nerase 9\ndefragment\ndefragment\ndefragment\nerase 1\nalloc 70\nerase 9\n', 'output': ['1\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\nNULL\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\n2\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n3\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '26 25\nalloc 25\nerase 1\nalloc 24\nerase 2\nalloc 23\nerase 3\nalloc 24\nerase 4\nalloc 24\nerase 5\nalloc 21\nerase 6\nalloc 24\nerase 7\nalloc 25\nerase 8\nalloc 25\nerase 9\nalloc 24\nerase 10\nalloc 25\nerase 11\nalloc 25\nerase 12\nalloc 25\nerase 13\n', 'output': ['1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n']}, {'input': '22 9\nalloc 9\nerase 1\nalloc 9\nerase 2\nalloc 9\nerase 3\nalloc 9\nerase 4\nalloc 9\nerase 5\nalloc 9\nerase 6\nalloc 9\nerase 7\nalloc 9\nerase 8\nalloc 9\nerase 9\nalloc 9\nerase 10\nalloc 9\nerase 11\n', 'output': ['1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n']}, {'input': '7 6\nalloc 1\nalloc 2\nalloc 3\nerase 1\ndefragment\nerase 3\nalloc 4\n', 'output': ['1\n2\n3\n4\n']}, {'input': '3 1\nerase -1\nerase 0\nerase -2147483648\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '7 100\nalloc 100\nerase 2147483647\nerase 1\nalloc 50\nalloc 50\nerase 3\nerase -2147483648\n', 'output': ['1\nILLEGAL_ERASE_ARGUMENT\n2\n3\nILLEGAL_ERASE_ARGUMENT\n']}, {'input': '12 10\nalloc 6\nalloc 2\nerase 1\nalloc 4\nalloc 2\nerase 3\nalloc 2\nalloc 3\nalloc 1\nalloc 1\nalloc 1\nalloc 1\n', 'output': ['1\n2\n3\n4\n5\nNULL\n6\n7\n8\n9\n']}, {'input': '8 50\nalloc 51\ndefragment\nalloc 100\ndefragment\nerase 1\nalloc 50\ndefragment\nalloc 50\n', 'output': ['NULL\nNULL\nILLEGAL_ERASE_ARGUMENT\n1\nNULL\n']}, {'input': '10 10\nalloc 10\nerase -1\nerase 1\nalloc 5\nerase -1\nalloc 5\nerase 0\nalloc 5\nerase 0\nalloc 5\n', 'output': ['1\nILLEGAL_ERASE_ARGUMENT\n2\nILLEGAL_ERASE_ARGUMENT\n3\nILLEGAL_ERASE_ARGUMENT\nNULL\nILLEGAL_ERASE_ARGUMENT\nNULL\n']}, {'input': '16 10\nalloc 10\ndefragment\ndefragment\ndefragment\nalloc 10\nerase 1\nerase 2\nalloc 6\ndefragment\ndefragment\nalloc 4\ndefragment\ndefragment\nerase 3\ndefragment\nalloc 6\n', 'output': ['1\nNULL\nILLEGAL_ERASE_ARGUMENT\n2\n3\nNULL\n']}, {'input': '16 10\nalloc 10\ndefragment\ndefragment\ndefragment\nalloc 10\nerase 1\nerase 2\nalloc 6\ndefragment\ndefragment\nalloc 4\ndefragment\ndefragment\nerase 2\ndefragment\nalloc 6\n', 'output': ['1\nNULL\nILLEGAL_ERASE_ARGUMENT\n2\n3\n4\n']}]


Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k=1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k=2, they do not rhyme (ommit≠ermit).Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):   Clerihew (aabb);  Alternating (abab);  Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.

[{'input': '1 1\nday\nmay\nsun\nfun\n', 'output': ['aabb\n']}, {'input': '1 1\nday\nmay\ngray\nway\n', 'output': ['aaaa\n']}, {'input': '2 1\na\na\na\na\na\na\ne\ne\n', 'output': ['aabb\n']}, {'input': '2 1\nday\nmay\nsun\nfun\ntest\nhill\nfest\nthrill\n', 'output': ['NO\n']}, {'input': '2 5\na\na\na\na\na\na\ne\ne\n', 'output': ['NO\n']}, {'input': '1 1\nrezwbgy\nxakgmv\njogezwbgy\napezwbgy\n', 'output': ['NO\n']}, {'input': '2 1\nnuqfxwrb\napqfkw\nuqfxwrb\nnhcuqfxwrb\nogkznwncmt\nevf\nogkznwncmt\nogkznwncmt\n', 'output': ['NO\n']}, {'input': '1 1\naawjvkxx\nawjvkxx\nxawjvkxx\nawjvkxx\n', 'output': ['aaaa\n']}, {'input': '2 2\nrhcujgxabk\nnjgdqpurul\nueoedt\ncpcfhbyvo\nzmfwnieog\npkpylassbf\nhrfeod\ncdwuil\n', 'output': ['NO\n']}, {'input': '2 1\nol\nol\nol\nzol\nek\nek\nek\nqek\n', 'output': ['aaaa\n']}, {'input': '3 2\nexdaoao\nrdwunurp\ndunurp\ntyqzuxao\ndupocgsps\nzsiravcm\nnqiravcm\nlnupocgsps\niwashk\neepkqcykbv\nyviwashk\neepkqcykbv\n', 'output': ['NO\n']}, {'input': '2 1\ndaihacbnhgfts\nsqihpntjvczkw\nmihpntjvczkw\nvyacbnhgfts\ntsvovdpqajmgvcj\ncexqkwrvctomb\njxbomb\ngnpajmgvcj\n', 'output': ['abba\n']}, {'input': '3 2\netba\ntfecetba\nzkitbgcuuy\nuuy\nbuxeoi\nmekxoi\nblviwoehy\niwoehy\njyfpaqntiz\nqvaqntiz\nhciak\niak\n', 'output': ['aabb\n']}, {'input': '4 3\niixxiojrrdytjcbkvymw\nbjqixxiojrrdytjcbkvymw\nogjixxiojrrdytjcbkvymw\nevixxpfxpgicpg\njkotitixiughfhphliuurx\ngyubkqtonejprfjzvqxbdpn\ndpudxfoqnhekjytbwiuurx\noubkqtonejprfjzvqxbdpn\npgzaendrxjhsfzjmijv\npomuaendrxjhsfzjmijv\nafyuyxueaendrxjhsfzjmijv\naendrxjhsfzjmijv\nyubweicj\ntbnsuxqigmxdfnmbipubweicj\nfuftydlmoo\nmdkuftydlmoo\n', 'output': ['NO\n']}, {'input': '5 2\nqurcmcbxyoddgyyccsmb\nlsdzsqoa\neurcmcbxyoddgyyccsmb\noa\nutyxmdhcvaclynmstwsx\nmkyycelbmkmdrilmbvr\nutyxmdhcvaclynmstwsx\nrduyelbmkmdrilmbvr\nhmguhvqswwciowwgu\nnoe\nzmyncuwrowwgu\nqrhymghavvbmigzsjoe\nbvofhknbzusykztlxwms\nbpbfmvjaimkdeddy\neofhknbzusykztlxwms\nmhivpkxkpazimkdeddy\negvywnhmfngllaknmn\nmblkvhenlggoftwjgk\nzegvywnhmfngllaknmn\ngrdenlggoftwjgk\n', 'output': ['abab\n']}, {'input': '7 3\nferwljzwakxedlgwl\noerwljzwakxedlgwl\nhyqombizhuhxedprb\netptjrizhuhxedprb\nurtuckar\ndkartmwramklcmi\nrurtuckar\nnurartmwramklcmi\niraziomsv\nsaziomsv\nbprapiqpayzurgij\nusyemayzurgij\nztstmeecvmkvuu\nquexlecvmkvuu\nrlhwecvmkvuu\nzecvmkvuu\niikymgbncljtub\nqiikymgbncljtub\nbcavhexqamyszgfya\nojexqamyszgfya\nieyxqinjinjv\nxtiudieyxqinjinjv\nthtceyxqinjinjv\nmuneyxqinjinjv\nwreae\nqylcjhjzfhteae\nozcjthgyuchqo\nfcjozcjthgyuchqo\n', 'output': ['NO\n']}, {'input': '16 1\ni\ni\ni\ni\ni\nu\ni\ni\no\na\na\no\na\ni\na\na\ni\ni\no\no\ni\ni\ni\ni\nu\nu\nu\nu\no\ne\ne\ne\no\ni\no\ni\na\na\na\na\nu\no\no\nu\ni\no\no\ni\na\na\ne\ne\na\na\na\na\na\no\na\na\nu\na\nu\nu\n', 'output': ['NO\n']}, {'input': '16 1\neb\neb\nfe\nce\ner\ner\new\new\nu\ncu\nu\nu\nud\nik\nud\nik\nve\niw\niw\nne\nel\nob\nel\nob\no\neo\no\nyo\nav\nav\nei\nmi\nu\noh\noh\nzu\niw\niw\na\nma\ni\nu\nku\ngi\nac\no\no\nac\ni\ner\nai\ner\nyu\nuf\nuf\nhu\nef\nef\nef\nef\nmu\nu\nqe\nie\n', 'output': ['NO\n']}, {'input': '25 1\nw\ni\nv\nx\nh\ns\nz\ny\no\nn\nh\ni\nf\nf\ny\nr\nb\nu\no\np\nz\nh\nt\no\nw\nx\nh\no\nj\ny\nw\nj\ny\nh\nh\nr\ns\nb\ny\nr\nw\no\nl\nl\nh\nh\nw\nu\na\nv\no\nx\nd\nw\nc\nf\ni\ne\nj\nq\nk\na\ne\nl\nw\nm\nf\na\nc\na\nb\nf\nj\nb\nx\ni\nx\ne\nu\nh\nm\no\ni\nq\nm\nk\nn\nd\nl\np\nc\nw\nu\nz\nc\nk\ng\ny\nj\ny\n', 'output': ['NO\n']}, {'input': '1 1\ne\ne\ne\ne\n', 'output': ['aaaa\n']}, {'input': '1 1\na\ne\ne\ne\n', 'output': ['NO\n']}, {'input': '1 1\ne\na\ne\ne\n', 'output': ['NO\n']}, {'input': '1 1\na\na\ne\ne\n', 'output': ['aabb\n']}, {'input': '1 1\ne\ne\na\ne\n', 'output': ['NO\n']}, {'input': '1 1\na\ne\na\ne\n', 'output': ['abab\n']}, {'input': '1 1\ne\na\na\ne\n', 'output': ['abba\n']}, {'input': '1 1\na\na\na\ne\n', 'output': ['NO\n']}, {'input': '1 1\ne\ne\ne\na\n', 'output': ['NO\n']}, {'input': '1 1\na\ne\ne\na\n', 'output': ['abba\n']}, {'input': '1 1\ne\na\ne\na\n', 'output': ['abab\n']}, {'input': '1 1\na\na\ne\na\n', 'output': ['NO\n']}, {'input': '1 1\ne\ne\na\na\n', 'output': ['aabb\n']}, {'input': '1 1\na\ne\na\na\n', 'output': ['NO\n']}, {'input': '1 1\ne\na\na\na\n', 'output': ['NO\n']}, {'input': '1 1\na\na\na\na\n', 'output': ['aaaa\n']}, {'input': '1 2\neraub\nbee\naab\nttbee\n', 'output': ['NO\n']}, {'input': '10 1\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\na\ny\n', 'output': ['NO\n']}, {'input': '1 2\neeereaatktb\nbee\niaattb\nottbee\n', 'output': ['NO\n']}, {'input': '1 1\nab\nac\nad\naf\n', 'output': ['NO\n']}, {'input': '1 1\nar\nat\nay\naw\n', 'output': ['NO\n']}, {'input': '2 1\na\ne\na\ne\na\na\na\na\n', 'output': ['abab\n']}, {'input': '1 1\na\ne\na\ni\n', 'output': ['NO\n']}, {'input': '1 1\na\ne\na\ne\n', 'output': ['abab\n']}, {'input': '1 1\nabbbbbbbbbbbbbbbbcbbbbbbbbbbbbbbbb\nabbbbbbbbbbbbbbbbfbbbbbbbbbbbbbbbb\nabbbbbbbbbbbbbbbbxbbbbbbbbbbbbbbbb\nabbbbbbbbbbbbbbbbdbbbbbbbbbbbbbbbb\n', 'output': ['NO\n']}, {'input': '2 1\na\ne\ne\na\na\na\na\na\n', 'output': ['abba\n']}, {'input': '1 1\nbug\nsuy\nluh\ngut\n', 'output': ['NO\n']}, {'input': '1 1\nam\nat\nan\nag\n', 'output': ['NO\n']}, {'input': '2 1\na\na\ne\ne\na\na\na\na\n', 'output': ['aabb\n']}, {'input': '1 4\naieoabcd\naeioabcd\naoeiabcd\naoieabcd\n', 'output': ['NO\n']}, {'input': '1 2\naec\naed\naek\naem\n', 'output': ['NO\n']}, {'input': '1 1\nar\nab\nak\naz\n', 'output': ['NO\n']}, {'input': '2 1\na\na\na\na\na\nb\nb\nb\n', 'output': ['NO\n']}]


#include <stdio.h>
#include <stdbool.h>
#include <memory.h>
#define N 1000

bool dfs(int i, const int incid[2][N][N+1], bool whatta[2][N]) {
	int j, k;
	if (whatta[0][i])
		return false;
	whatta[0][i] = true;
	for (j = 1; j <= incid[0][i][0]; j ++) {
		int jj = incid[0][i][j];
		if (whatta[1][jj])
			continue;
		whatta[1][jj] = true;
		for (k = 1; k <= incid[1][jj][0]; k ++) {
			int kk = incid[1][jj][k];
			(void) dfs(kk, incid, whatta);
		};
	};
	return true;
};

int main(void) {
	int incid[2][N][N+1];
	bool whatta[2][N];
	int ctx;
	int n, i, j, k;
	memset(incid, 0, sizeof incid);
	memset(whatta, 0, sizeof whatta);
	scanf("%d", &n);
	for (i = 0; i < n; i ++) {
		scanf("%d%d", &j, &k); --j; --k;
		incid[0][j][++incid[0][j][0]] = k;
		incid[1][k][++incid[1][k][0]] = j;
	};
	ctx = 0;
	for (i = 0; i < N; i ++)
		if (incid[0][i][0])
			if (dfs(i, incid, whatta))
				++ctx;
	--ctx;
	printf("%d\n", ctx);
	return 0;
};

#include<stdio.h>

int main(){
	int n,i,j,k;
	struct pair{
		int x,y;
	};
	scanf("%d",&n);
	int arr[n+1];
	int count[n+1];
	struct pair loc[n+1];
	for(i = 1 ; i < n+1 ; i++){
		arr[i] = i;
		count[i] = 0;
		scanf("%d%d",&loc[i].x,&loc[i].y);
	}

	int temp;
	for(i = 1 ; i < n+1 ; i++){
		for(j = i+1 ; j < n+1 ; j++){
			if(loc[i].x == loc[j].x || loc[i].y == loc[j].y){
				temp = arr[j];
				arr[j] = arr[i];
				for(k = 1 ; k < n+1 ; k++){
					if(arr[k] == temp){
						arr[k] = arr[i];
					}
				}
			}
		}
	}
	int res = 0;
	for(i = 1 ; i < n+1 ; i++){
		temp = arr[i];
		if(count[temp] == 0){
			count[temp]++;
			res++;
		}
	}
/*
	for(i = 1 ; i < n+1 ; i++){
		printf("i->%d",arr[i]);
		printf("(%d,%d)\n",loc[i].x,loc[i].y);
	}
*/
	printf("%d",res-1);
}

Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.


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

main()
{
	char a[3005],s;
	int len,i,count,ans=0;

	scanf("%d%s",&i,a);
	len = strlen(a);

	i=0,count=0;

		while(a[i]=='.')
		{
			count++;
			i++;
		}
		if(a[i]=='R')
			ans+=count;
		s=a[i];
		i++;

	count=0;
	while(i<len)
	{
		while(a[i]=='.')
		{
			count++;
			i++;
		}
		if(s=='R')
		{
			if(count%2==1 && i<len)
				ans+=1;
		}
		else if(s=='L')
		{
			ans+=count;
		}
		s=a[i];
		i++;
		count=0;
	}
	if(s=='R' && i<len)
		ans-=1;

	count=0;
	for(i=0;i<len;i++)
	{
		if(a[i]=='.')
			count++;
		else break;
	}
	if(i==len)
		ans = count;
	printf("%d\n",ans);

	return 0;
}

Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!


#include<stdio.h>
void QuickSort(int *array, int from, int to);
int main()
{
    int n,l,i,p=0,s=0,c,j,f=0;
    scanf("%d%d",&n,&l);
    int a[100];
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
    QuickSort(a,0,n-1);
    for(i=0;i<n;i++)
    {
        if(a[i]==l) f=1;
        if(a[i]>=l)
        {
            c=0;
            for(j=i;j<n;j++)
            c=c+(a[j]/a[i]);
            s=a[i]*c;
            if(s>p)
            p=s;
        }
    }
    if(f==0)
    {
    c=0;
    for(i=0;i<n;i++)
    c=c+a[i]/l;
    s=l*c;
    if(s>p)
    p=s;
    }
    printf("%d",p);
    return 0;
}
void QuickSort(int *array, int from, int to)
{
        if(from>=to)return;
        int pivot = array[from];
        int i = from, j, temp;
        for(j = from + 1;j <= to;j++)
        {
                if(array[j] < pivot)
                {
                        i = i + 1;
                        temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                }
        }
        temp = array[i];
        array[i] = array[from];
        array[from] = temp;
        QuickSort(array,from,i-1);
        QuickSort(array,i+1,to);
}

#include<stdio.h>
int cmp(const void *a,const void *b)
{
    return *(int *)a-*(int *)b;
}
int main()
{
    int i,j,l[100],n,pro=0,k,q,p,r=0;
    scanf("%d %d",&n,&k);
    for(i=0;i<n;i++)
        {
            scanf("%d",&l[i]);
            q=l[i]/k;
            r+=q;
        }
    pro=r*k;
    qsort(l,n,sizeof(int),cmp);
    for(i=0;i<n;i++)
        {
            r=0;
            if(l[i]>=k)
            {
                for(j=i;j<n;j++)
                {
                   q= l[j]/l[i];
                   r+=q;
                }
                p=r*l[i];
                if(p>pro)
                    pro=p;
            }
        }
    printf("%d",pro);
    return(0);
}

The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths)Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe)After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way.Thus, if the blinds consist of k pieces each d in length, then they are of form of a rectangle of k×d bourlemeters. Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than l bourlemeter. The window is of form of a rectangle with side lengths as positive integers.


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

int main(void) {
    int n, k, i, j, p, same;
    int cost, minimum = 10000000, ind[11][10002], samenum[11] = {0};
    char inp[10001], res[10001], result[10001] = "";

    scanf("%d%d%s", &n, &k, inp);

    for (i = 0; i < n; i++) {
        samenum[inp[i] - '0']++;
        ind[inp[i] - '0'][0]++;
        ind[inp[i] - '0'][ind[inp[i] - '0'][0]] = i;
    }

    for (i = 0; i < 10; i++) {
        strcpy(res, inp);
        cost = 0;
        same = samenum[i];

        for (p = 1; p < 10; p++) {
            if (i + p >= 0 && i + p <= 9) {
                for (j = 1; j <= ind[i + p][0] && same < k; j++) {
                    cost += abs(res[ind[i + p][j]] - '0' - i);
                    res[ind[i + p][j]] = '0' + i;
                    same++;
                }
            }
            if (i - p >= 0 && i - p <= 9) {
                for (j = ind[i - p][0]; j >= 1 && same < k; j--) {
                    cost += abs(res[ind[i - p][j]] - '0' - i);
                    res[ind[i - p][j]] = '0' + i;
                    same++;
                }
            }
        }
        if ((minimum > cost) || (minimum == cost && strcmp(result, res) > 0)) {
            strcpy(result, res);
            minimum = cost;
        }
        //printf("%d\n%s\n", cost, res);
    }
    printf("%d\n%s\n", minimum, result);
    return 0;
}

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

#define L 10010
#define D 10
#define INF 0x3f3f3f3f

int n, m;
char num[L];
int best_cost;
char best_result[L];

void solve(int e) {
  int i, d, j, k, cost;
  static char result[L];
  static int idx[D][L], len[D];

  memset(len, 0, sizeof len);
  for (i = 0; i < n; i++) {
    d = num[i] - '0';
    k = abs(d - e);
    if (d > e) idx[k][len[k]++] = i;
  }
  for (i = n - 1; i >= 0; i--) {
    d = num[i] - '0';
    k = abs(d - e);
    if (d <= e) idx[k][len[k]++] = i;
  }

  k = m;
  cost = 0;
  strcpy(result, num);
  for (i = 0; k && i < 10; i++)
    for (j = 0; k && j < len[i]; j++, k--) {
      cost += i;
      result[idx[i][j]] = '0' + e;
    }
  if (cost < best_cost || cost == best_cost && strcmp(result, best_result) < 0) {
    best_cost = cost;
    strcpy(best_result, result);
  }
}

int main() {
  int e;

  scanf("%d %d", &n, &m);
  scanf("%s", num);
  best_cost = INF;
  for (e = 0; e < 10; e++)
    solve(e);
  printf("%d\n", best_cost);
  printf("%s\n", best_result);

  return 0;
}

A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one.Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one.


#include <stdio.h>

#define inc 0
#define dec 1

#define max(a,b) (a>b?(a):(b))

int h[1001];
int a[1001][2];

int main(){
    int n,i,answer;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
        scanf("%d",&h[i]);
    a[1][inc] = 1;
    for(i=2;i<=n;i++){
        if(h[i]>=h[i-1])
            a[i][inc] = 1 + a[i-1][inc];
        else
            a[i][inc] = 1;
    }
    a[n][dec] = 1;
    for(i=n-1;i>=1;i--){
        if(h[i]>=h[i+1])
            a[i][dec] = a[i+1][dec] + 1;
        else
            a[i][dec] = 1;
    }
    answer = -1;
    for(i=1;i<=n;i++)
        answer = max(answer,a[i][inc]+a[i][dec]);
    printf("%d\n",answer-1);

}

Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1×n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1×5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture: As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.


#include<stdio.h>
int main()
{
    long long int n,i,sum=0,j,k;
    scanf("%lld",&n);
    long long int a[n],b[5],c[5]={0};
    for(i=0;i<n;i++){
        scanf("%lld",&a[i]);
    }
    for(i=0;i<5;i++){
        scanf("%lld",&b[i]);
    }
    for(i=0;i<n;i++){
        sum+=a[i];
        for(j=4;j>=0;j--){
            if(sum<b[0])break;
            if(sum>=b[j]){
                c[j]+=sum/b[j];
                k=sum/b[j];
                sum=sum%b[j];
            }
        }
        //printf("%d\n",j);
    }
    for(i=0;i<5;i++)printf("%lld ",c[i]);
    printf("\n%lld",sum);
    return 0;
}

Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1,p2,...,pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.


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

struct house {
  int x, a;
} *h;

int compare(const void *a, const void *b){
  struct house *pa = (struct house *) a;
  struct house *pb = (struct house *) b;
  return (*pa).x - (*pb).x;
}

int main(){
  int n, t, i, cnt = 2;
  scanf("%d%d", &n, &t);
  h = malloc(sizeof(struct house) * n);
  for (i=0; i<n; i++)
    scanf("%d%d", &h[i].x, &h[i].a);
  qsort(h, n, sizeof(struct house), compare);
  for (i=1; i<n; i++){
    double l = h[i - 1].x + (double) h[i - 1].a / 2;
    double r = h[i].x - (double) h[i].a / 2;
    if (r - l >= t){
      cnt++;
      if (r - l > t) cnt++;
    }
  }
  printf("%d\n", cnt);
}

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

int x[1101], a[1101];

int main ()
{
	int n, i, j, t, ans = 0;
	scanf ("%d %d", &n, &t);
	for (i=1;i<=n;++i)
		scanf ("%d %d", &x[i], &a[i]);
	for (i =-4400;i<=4400;++i)
	{
		int b = 0;
		for (j=1;j<=n;++j)
		{
			int k=abs(x[j]*2-i);
			if (k == t + a[j])
				b=1;
			else if (k < t + a[j])
				break;
		}
		if (j > n)
			ans+=b;
	}
	printf ("%d\n", ans);
	return 0;
}

A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?


#include <stdio.h>

enum { N = 100000 };

int
main(void)
{
    int i, k, n, a[N], ok[N];
    scanf("%d", &n);
    for (i = 0; i < n; ++i) {
        scanf("%d", a + i);
    }

    for (k = 1; k <= n; ++k) {
        if (n % k) continue;
        if (n / k < 3) continue;
        for (i = 0; i < k; ++i) {
            ok[i] = 1;
        }
        for (i = 0; i < n; ++i) {
            ok[i % k] &= a[i];
        }
        for (i = 0; i < k; ++i) {
            if (ok[i]) {
                printf("YES\n");
                return 0;
            }
        }
    }
    printf("NO\n");

    return 0;
}

#include <stdio.h>

int knights[100500], n;

char check(int k) {
    int start, j;
    if(n / k < 3)
        return 0;
    for(start = 0; start < k; start++) {
        char isHappy = 1;
        for(j = start; isHappy && j < n; j += k) {
            if(knights[j] == 0) {
                isHappy = 0;
            }
        }
        if(isHappy)
            return 1;
    }
    return 0;
}

int main() {
    int i, j;
    scanf("%d", &n);
    for(i = 0; i < n; i++) {
        scanf("%d", knights + i);
    }
    for(i = 1; (long long)(i) * i <= n; i++) {
        if(n % i)
            continue;
        if(check(i) || check(n / i)) {
            puts("YES");
            return 0;
        }
    }
    puts("NO");
    return 0;
}

There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood. King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.


Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.


#include <stdio.h>

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

   int cur = 1, add = 1, r = 0;
   for(r = 0; r < n-1; ++r){
      cur += add;
      add++;
      if(cur > n) cur -= n;
      printf("%d ", cur);
   }

   return 0;
}

A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n=5, then after the third throw the child number 2 has the ball again. Overall, n-1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.


#include<stdio.h>

 int a[101], n, max = -1, i;
double b, c[101];

int main()
{
    scanf("%d %lf", &n, &b);
    for(i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
        if(a[i] > max)
            max = a[i];
    }
    for(i = 0; i < n; i++)
    {
        if(a[i] < max)
        {
            c[i] = max - a[i];
            b -= c[i];
        }
        if(b < 0)
        {
            printf("-1");
            return 0;
        }
    }
    for(i = 0; i < n; i++)
    {
        printf("%lf\n",c[i] + b/n);
    }
    return 0;
}

#include<stdio.h>
int main()
{
    int n,b,i,c=0;double s=0.0,t;
    scanf("%d%d",&n,&b);
    (double)n;
    (double)b;
    int a[n];

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

t=(s+b)/n;
for(i=0;i<n;i++)
{
if((t-a[i])<0)
{printf("-1");
c++;
break;}

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

return 0;
}

A group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.Polycarpus has already began the process and he partially emptied the Ber-Cola bottle. Now the first mug has a1 milliliters of the drink, the second one has a2 milliliters and so on. The bottle has b milliliters left and Polycarpus plans to pour them into the mugs so that the main equation was fulfilled.Write a program that would determine what volume of the drink Polycarpus needs to add into each mug to ensure that the following two conditions were fulfilled simultaneously:   there were b milliliters poured in total. That is, the bottle need to be emptied;  after the process is over, the volumes of the drink in the mugs should be equal.


#include <stdio.h>

int main()
{
    int n, a, b;
    int cur1, cur2;
    int i, j;
    int flag;

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

    if (n > a*b)
    {
        printf("-1");
    }
    else
    {
        cur1 = 1;
        cur2 = 2;
        for (i = 0; i < a; i++)
        {
            if (i%2 == 0)
            {
                flag = 1;
            }
            else
            {
                flag = 0;
            }
            for (j = 0; j < b; j++)
            {
                if (flag)
                {
                    if (cur1 <= n)
                    {
                        printf("%d ", cur1);
                        cur1 += 2;
                        flag = 0;
                    }
                    else
                    {
                        printf("0 ");
                        flag = 0;
                    }
                }
                else
                {
                    if (cur2 <= n)
                    {
                        printf("%d ", cur2);
                        cur2 += 2;
                        flag = 1;
                    }
                    else
                    {
                        printf("0 ");
                        flag = 1;
                    }
                }
            }
            printf("\n");
        }
    }

    return 0;
}

There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a×b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.


An African crossword is a rectangular table n×m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.

[{'input': '3 3\ncba\nbcd\ncbc\n', 'output': ['abcd']}, {'input': '5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf\n', 'output': ['codeforces']}, {'input': '4 4\nusah\nusha\nhasu\nsuha\n', 'output': ['ahhasusu']}, {'input': '7 5\naabcd\neffgh\niijkk\nlmnoo\npqqrs\nttuvw\nxxyyz\n', 'output': ['bcdeghjlmnprsuvwz']}, {'input': '10 10\naaaaaaaaaa\nbccceeeeee\ncdfffffffe\ncdfiiiiile\ncdfjjjjile\ndddddddile\nedfkkkkile\nedddddddde\ngggggggggg\nhhhhhhhhhe\n', 'output': ['b']}, {'input': '15 3\njhg\njkn\njui\nfth\noij\nyuf\nyfb\nugd\nhgd\noih\nhvc\nugg\nyvv\ntdg\nhgf\n', 'output': ['hkniftjfbctd']}, {'input': '17 19\nbmzbmweyydiadtlcoue\ngmdbyfwurpwbpuvhifn\nuapwyndmhtqvkgkbhty\ntszotwflegsjzzszfwt\nzfpnscguemwrczqxyci\nvdqnkypnxnnpmuduhzn\noaquudhavrncwfwujpc\nmiggjmcmkkbnjfeodxk\ngjgwxtrxingiqquhuwq\nhdswxxrxuzzfhkplwun\nfagppcoildagktgdarv\neusjuqfistulgbglwmf\ngzrnyxryetwzhlnfewc\nzmnoozlqatugmdjwgzc\nfabbkoxyjxkatjmpprs\nwkdkobdagwdwxsufees\nrvncbszcepigpbzuzoo\n', 'output': ['lcorviunqvgblgjfsgmrqxyivyxodhvrjpicbneodxjtfkpolvejqmllqadjwotmbgxrvs']}, {'input': '1 1\na\n', 'output': ['a']}, {'input': '2 2\nzx\nxz\n', 'output': ['zxxz']}, {'input': '1 2\nfg\n', 'output': ['fg']}, {'input': '2 1\nh\nj\n', 'output': ['hj']}, {'input': '1 3\niji\n', 'output': ['j']}, {'input': '3 1\nk\np\nk\n', 'output': ['p']}, {'input': '2 3\nmhw\nbfq\n', 'output': ['mhwbfq']}, {'input': '3 2\nxe\ner\nwb\n', 'output': ['xeerwb']}, {'input': '3 7\nnutuvjg\ntgqutfn\nyfjeiot\n', 'output': ['ntvjggqfnyfjeiot']}, {'input': '5 4\nuzvs\namfz\nwypl\nxizp\nfhmf\n', 'output': ['uzvsamfzwyplxizphm']}, {'input': '8 9\ntjqrtgrem\nrwjcfuoey\nywrjgpzca\nwabzggojv\najqmmcclh\nozilebskd\nqmgnbmtcq\nwakptzkjr\n', 'output': ['mrjcfuyyrjpzabzvalhozilebskdgnbtpzr']}, {'input': '9 3\njel\njws\ntab\nvyo\nkgm\npls\nabq\nbjx\nljt\n', 'output': ['elwtabvyokgmplabqbxlt']}, {'input': '7 6\neklgxi\nxmpzgf\nxvwcmr\nrqssed\nouiqpt\ndueiok\nbbuorv\n', 'output': ['eklgximpzgfvwcmrrqedoiqptdeiokuorv']}, {'input': '14 27\npzoshpvvjdpmwfoeojapmkxjrnk\nitoojpcorxjdxrwyewtmmlhjxhx\ndoyopbwusgsmephixzcilxpskxh\nygpvepeuxjbnezdrnjfwdhjwjka\nrfjlbypoalbtjwrpjxzenmeipfg\nkhjhrtktcnajrnbefhpavxxfnlx\nvwlwumqpfegjgvoezevqsolaqhh\npdrvrtzqsoujqfeitkqgtxwckrl\nxtepjflcxcrfomhqimhimnzfxzg\nwhkfkfvvjwkmwhfgeovwowshyhw\nolchgmhiehumivswgtfyhqfagbp\ntdudrkttpkryvaiepsijuejqvmq\nmuratfqqdbfpefmhjzercortroh\nwxkebkzchupxumfizftgqvuwgau\n', 'output': ['zshdanicdyldybwgclygzrhkayatwxznmicbpvlupfsoewcleploqngsyolceswtyqbpyasmuadbpcehqva']}, {'input': '1 100\nysijllpanprcrrtvokqmmupuptvawhvnekeybdkzqaduotmkfwybqvytkbjfzyqztmxckizheorvkhtyoohbswcmhknyzlgxordu\n', 'output': ['g']}, {'input': '2 100\ngplwoaggwuxzutpwnmxhotbexntzmitmcvnvmuxknwvcrnsagvdojdgaccfbheqojgcqievijxapvepwqolmnjqsbejtnkaifstp\noictcmphxbrylaarcwpruiastazvmfhlcgticvwhpxyiiqokxcjgwlnfykkqdsfmrfaedzchrfzlwdclqjxvidhomhxqnlmuoowg\n', 'output': ['rbe']}, {'input': '3 100\nonmhsoxoexfwavmamoecptondioxdjsoxfuqxkjviqnjukwqjwfadnohueaxrkreycicgxpmogijgejxsprwiweyvwembluwwqhj\nuofldyjyuhzgmkeurawgsrburovdppzjiyddpzxslhyesvmuwlgdjvzjqqcpubfgxliulyvxxloqyhxspoxvhllbrajlommpghlv\nvdohhghjlvihrzmwskxfatoodupmnouwyyfarhihxpdnbwrvrysrpxxptdidpqabwbfnxhiziiiqtozqjtnitgepxjxosspsjldo\n', 'output': ['blkck']}, {'input': '100 1\na\nm\nn\nh\na\nx\nt\na\no\np\nj\nz\nr\nk\nq\nl\nb\nr\no\ni\ny\ni\np\ni\nt\nn\nd\nc\nz\np\nu\nn\nw\ny\ng\ns\nt\nm\nz\ne\nv\ng\ny\nj\nd\nz\ny\na\nn\nx\nk\nd\nq\nn\nv\ng\nk\ni\nk\nf\na\nb\nw\no\nu\nw\nk\nk\nb\nz\nu\ni\nu\nv\ng\nv\nx\ng\np\ni\nz\ns\nv\nq\ns\nb\nw\ne\np\nk\nt\np\nd\nr\ng\nd\nk\nm\nf\nd\n', 'output': ['hlc']}, {'input': '100 2\nhd\ngx\nmz\nbq\nof\nst\nzc\ndg\nth\nba\new\nbw\noc\now\nvh\nqp\nin\neh\npj\nat\nnn\nbr\nij\nco\nlv\nsa\ntb\nbl\nsr\nxa\nbz\nrp\nsz\noi\nec\npw\nhf\njm\nwu\nhq\nra\npv\ntc\ngv\nik\nux\ntz\nbf\nty\ndk\nwo\nor\nza\nkv\nqt\nfa\njy\nbk\nuv\ngk\ncz\nds\nie\noq\nmf\nxn\nql\nxs\nfb\niv\ncj\nkn\nns\nlg\nji\nha\naj\ndg\nfj\nut\nsg\nju\noc\nov\nhe\nnw\nbl\nlp\nbx\nnm\nyq\ncw\nov\nxk\npg\noh\npl\nuo\ngf\nul\n', 'output': ['dvy']}, {'input': '100 3\nruy\nmye\njgp\nscn\nktq\nalx\nmvk\nlpm\nkry\norb\nmpu\nzcv\nlge\nkft\ndzp\ntfb\nhqz\nuur\nhry\nzjx\ncuo\nqqc\ntih\nenj\nvnp\nbwi\nzzh\nhkc\nwdr\nldh\nvel\nizj\nfhb\nqrn\nqpp\nvzs\nlhg\nkee\nlbq\nzhy\nwcl\nyaa\nton\nfly\nkyw\nept\ngwq\ncoe\nopd\neez\nnmx\nnjg\nwhy\nvel\nafq\nnbq\nulx\noxs\nbbo\nyhx\nfmz\nnrg\nnfm\njek\nbeu\ntya\nxgs\nsgg\nnkq\nbbv\nwkd\ntns\nfdt\neox\nobc\neab\nkkj\noub\ngji\nrht\nozv\nysk\nsbt\nflf\npbu\nlxb\npzs\nrzh\ncea\nkmi\nuea\nncc\nzng\nvkn\njhn\njqw\nlqc\nmbt\nlov\ngam\n', 'output': ['tvdiixs']}]


#include <stdio.h>

int arr[5010]={0};

int main(void){
	int i;
	int n;
	int sum=0;
	scanf("%d",&n);
	for(i=0;i<n;i++){
		int x;
		scanf("%d",&x);
		arr[x]++;
	}
	for(i=1;i<=n;i++){
		if(arr[i]) sum+=arr[i]-1;
	}
	for(;i<=5000;i++){
		if(arr[i]) sum+=arr[i];
	}
	printf("%d\n",sum);
}

"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1,a2,...,an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).


#include<stdio.h>
int main()
{
    int n,m,i,j,sn[50],sm[50],max,count;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    scanf("%d",sn+i);
    scanf("%d",&m);
    for(i=0;i<m;i++)
    scanf("%d",sm+i);
    max=0;
    count=0;
    for(i=0;i<n;i++)
    for(j=0;j<m;j++)
    {
        if(sm[j]%sn[i]==0)
        {
           if(sm[j]/sn[i]>max)
           {
              max=sm[j]/sn[i];
              count=1;
           }
           else if(sm[j]/sn[i]==max)
           {
              count++;
           }
        }
    }
    printf("%d\n",count);
    //system("pause");
    return 0;
}

Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0<a1<a2<...<an) teeth, and the j-th star on the rear wheel axle has bj (0<b1<b2<...<bm) teeth. Any pair (i,j) (1≤i≤n; 1≤j≤m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i,j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i,j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i,j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.


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

int main()
{
    char s1[201];
    gets(s1);
    char s2[201];
    gets(s2);
    int i,j;
    int ff=strlen(s2);
    int ss=0;
    for(i=0;i<strlen(s2);i++){
        for(j=0;j<strlen(s1)&&s2[i]!='\t'&&s2[i]!=' ';j++){
            if(s2[i]==s1[j]){
                ss++;
                s1[j]='0';
                break;
            }
        }
        if(s2[i]=='\t'||s2[i]==' '){
            ff--;
        }
    }
    if(ss==ff){
        printf("YES");
    }
    else{
        printf("NO");
    }
    return 0;
}

main()
{
	char str[200];
    int i=0,hash[256]={0};
    gets(str);
    while(str[i])   hash[str[i++]]++;
    gets(str);
    i=0;
    while(str[i])   hash[str[i++]]--;
    i=0;
    while(i<256)
    {
        if(hash[i]<0 && i!=' ')
        {
            printf("NO\n");
            return 0;
        }
        i++;
    }
    printf("YES\n");
    return 0;
}

Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

[{'input': 'Instead of dogging Your footsteps it disappears but you dont notice anything\nwhere is your dog\n', 'output': ['NO\n']}, {'input': 'Instead of dogging Your footsteps it disappears but you dont notice anything\nYour dog is upstears\n', 'output': ['YES\n']}, {'input': 'Instead of dogging your footsteps it disappears but you dont notice anything\nYour dog is upstears\n', 'output': ['NO\n']}, {'input': 'abcdefg hijk\nk j i h g f e d c b a\n', 'output': ['YES\n']}, {'input': 'HpOKgo\neAtAVB\n', 'output': ['NO\n']}, {'input': 'GRZGc\nLPzD\n', 'output': ['NO\n']}, {'input': 'GtPXu\nd\n', 'output': ['NO\n']}, {'input': 'FVF\nr \n', 'output': ['NO\n']}, {'input': 'HpOKgo\nogK\n', 'output': ['YES\n']}, {'input': 'GRZGc\nZG\n', 'output': ['YES\n']}, {'input': 'HpOKgoueAtAVBdGffvQheJDejNDHhhwyKJisugiRAH OseK yUwqPPNuThUxTfthqIUeb wS jChGOdFDarNrKRT  MlwKecxWNoKEeD BbiHAruE XMlvKYVsJGPP\nAHN  XvoaNwV  AVBKwKjr u      U K wKE D K   Jy KiHsR h d W  Js IHyMPK Br iSqe  E fDA   g H\n', 'output': ['YES\n']}, {'input': 'GRZGcsLPzDrCSXhhNTaibJqVphhjbcPoZhCDUlzAbDnRWjHvxLKtpGiFWiGbfeDxBwCrdJmJGCGv GebAOinUsFrlqKTILOmxrFjSpEoVGoTdSSstJWVgMLKMPettxHASaQZNdOIObcTxtF qTHWBdNIKwj\nWqrxze Ji x q aT GllLrRV jMpGiMDTwwS JDsPGpAZKACmsFCOS CD Sj  bCDgKF  jJxa RddtLFAi VGLHH SecObzG q  hPF \n', 'output': ['YES\n']}, {'input': 'GtPXuwdAxNhODQbjRslDDKciOALJrCifTjDQurQEBeFUUSZWwCZQPdYwZkYbrduMijFjgodAOrKIuUKwSXageZuOWMIhAMexyLRzFuzuXqBDTEaWMzVdbzhxDGSJC SsIYuYILwpiwwcObEHWpFvHeBkWYNitqYrxqgHReHcKnHbtjcWZuaxPBVPb\nTQIKyqFaewOkY lZUOOuxEw EwuKcArxRQGFYkvVWIAe SuanPeHuDjquurJu aSxwgOSw jYMwjxItNUUArQjO BIujAhSwttLWp\n', 'output': ['YES\n']}, {'input': 'FVFSr unvtXbpKWF vPaAgNaoTqklzVqiGYcUcBIcattzBrRuNSnKUtmdGKbjcE\nUzrU K  an GFGR        Wc zt iBa     P c    T K v p     V In   b           B   c\n', 'output': ['YES\n']}, {'input': 'lSwjnYLYtDNIZjxHiTawdh ntSzggZogcIZTuiTMWVgwyloMtEhqkrOxgIcFvwvsboXUPILPIymFAEXnhApewJXJNtFyZ\nAoxe  jWZ u  yImg  o AZ FNI w lpj  tNhT g y  ZYcb rc J    w Dlv\n', 'output': ['YES\n']}, {'input': 'kvlekcdJqODUKdsJlXkRaileTmdGwUHWWgvgUokQxRzzbpFnswvNKiDnjfOFGvFcnaaiRnBGQmqoPxDHepgYasLhzjDgmvaFfVNEcSPVQCJKAbSyTGpXsAjIHr\nGjzUllNaGGKXUdYmDFpqFAKIwvTpjmqnyswWRTnxlBnavAGvavxJemrjvRJc\n', 'output': ['YES\n']}, {'input': 'kWbvhgvvoYOhwXmgTwOSCDXrtFHhqwvMlCvsuuAUXMmWaYXiqHplFZZemhgkTuvsUtIaUxtyYauBIpjdbyYxjZ ZkaBPzwqPfqF kCqGRmXvWuabnQognnkvdNDtRUsSUvSzgBuxCMBWJifbxWegsknp\nBsH   bWHJD n Ca T xq  PRCv  tatn Wjy sm  I q s WCjFqdWe  t W XUs  Do  eb Pfh ii  hTbF  O Fll\n', 'output': ['YES\n']}, {'input': 'OTmLdkMhmDEOMQMiW ZpzEIjyElHFrNCfFQDp SZyoZaEIUIpyCHfwOUqiSkKtFHggrTBGkqfOxkChPztmPrsHoxVwAdrxbZLKxPXHlMnrkgMgiaHFopiFFiUEtKwCjpJtwdwkbJCgA bxeDIscFdmHQJLAMNhWlrZisQrHQpvbALWTwpf jnx\nDbZwrQbydCdkJMCrftiwtPFfpMiwwrfIrKidEChKECxQUBVUEfFirbGWiLkFQkdJiFtkrtkbIAEXCEDkwLpK\n', 'output': ['YES\n']}, {'input': 'NwcGaIeSkOva\naIa\n', 'output': ['YES\n']}, {'input': 'gSrAcVYgAdbdayzbKGhIzLDjyznLRIJH KyvilAaEddmgkBPCNzpmPNeGEbmmpAyHvUSoPvnaORrPUuafpReEGoDOQsAYnUHYfBqhdcopQfxJuGXgKnbdVMQNhJYkyjiJDKlShqBTtnnDQQzEijOMcYRGMgPGVhfIReYennKBLwDTVvcHMIHMgVpJkvzTrezxqS\nHJerIVvRyfrPgAQMTI AqGNO mQDfDwQHKgeeYmuRmozKHILvehMPOJNMRtPTAfvKvsoGKi xHEeKqDAYmQJPUXRJbIbHrgVOMGMTdvYiLui\n', 'output': ['YES\n']}, {'input': 'ReB hksbHqQXxUgpvoNK bFqmNVCEiOyKdKcAJQRkpeohpfuqZabvrLfmpZOMcfyFBJGZwVMxiUPP pbZZtJjxhEwvrAba\nJTCpQnIViIGIdQtLnmkVzmcbBZR CoxAdTtWSYpbOglDFifqIVQ vfGKGtLpxpJHiHSWCMeRcrVOXBGBhoEnVhNTPWGTOErNtSvokcGdgZXbgTEtISUyTwaXUEIlJMmutsdCbiyrPZPJyRdOjnSuAGttLy\n', 'output': ['NO\n']}, {'input': 'hrLzRegCuDGxTrhDgVvM KowwyYuXGzIpcXdSMgeQVfVOtJZdkhNYSegwFWWoPqcZoeapbQnyCtojgkcyezUNHGGIZrhzsKrvvcrtokIdcnqXXkCNKjrOjrnEAKBNxyDdiMVeyLvXxUYMZQRFdlcdlcxzKTeYzBlmpNiwWbNAAhWkMoGpRxkCuyqkzXdKWwGH\nJESKDOfnFdxPvUOCkrgSBEPQHJtJHzuNGstRbTCcchRWJvCcveSEAtwtOmZZiW\n', 'output': ['NO\n']}, {'input': 'yDBxCtUygQwWqONxQCcuAvVCkMGlqgC zvkfEkwqbhMCQxnkwQIUhucCbVUyOBUcXvTNEGriTBwMDMfdsPZgWRgIUDqM\neptVnORTTyixxmWIBpSTEwOXqGZllBgSxPenYCDlFwckJlWsoVwWLAIbPOmFqcKcTcoQqahetl KLfVSyaLVebzsGwPSVbtQAeUdZAaJtfxlCEvvaRhLlVvRJhKat IaB awdqcDlrrhTbRxjEbzGwcdmdavkhcjHjzmwbxAgw\n', 'output': ['NO\n']}, {'input': 'jlMwnnotSdlQMluKWkJwAeCetcqbIEnKeNyLWoKCGONDRBQOjbkGpUvDlmSFUJ bWhohqmmIUWTlDsvelUArAcZJBipMDwUvRfBsYzMdQnPDPAuBaeJmAxVKwUMJrwMDxNtlrtAowVWqWiwFGtmquZAcrpFsLHCrvMSMMlvQUqypAihQWrFMNoaqfs IBg\nNzeWQ bafrmDsYlpNHSGTBBgPl WIcuNhyNaNOEFvL\n', 'output': ['NO\n']}, {'input': 'zyWvXBcUZqGqjHwZHQryBtFliLYnweXAoMKNpLaunaOlzaauWmLtywsEvWPiwxJapocAFRMjrqWJXYqfKEbBKnzLO\npsbi bsXpSeJaCkIuPWfSRADXdIClxcDCowwJzGCDTyAl\n', 'output': ['NO\n']}, {'input': 'kKhuIwRPLCwPFfcnsyCfBdnsraGeOCcLTfXuGjqFSGPSAeDZJSS bXKFanNqWjpFnvRpWxHJspvisDlADJBioxXNbVoXeUedoPcNEpUyEeYxdJXhGzFAmpAiHotSVwbZQsuWjIVhVaEGgqbZHIoDpiEmjTtFylCwCkWWzUOoUfOHxEZvDwNpXhBWamHn\nK VpJjGhNbwCRhcfmNGVjewBFpEmPlIKeTuWiukDtEWpjgqciqglkyNfWrBLbGAKvlNWxaUelJmSlSoakSpRzePvJsshOsTYrMPXdxKpaShjyVIXGhRIAdtiGpNwtiRmGTBZhkJqIMdxMHX RMxCMYcWjcjhtCHyFnCvjjezGbkRDRiVxkbh\n', 'output': ['NO\n']}, {'input': 'AXssNpFKyQmJcBdBdfkhhMUzfqJVgcLBddkwtnFSzSRUCjiDcdtmkzIGkCKSxWUEGhmHmciktJyGMkgCductyHx\nI nYhmJfPnvoKUiXYUBIPIcxNYTtvwPUoXERZvY ahlDpQFNMmVZqEBiYqYlHNqcpSCmhFczBlOAhsYFeqMGfqL EJsDNOgwoJfBzqijKOFcYQ\n', 'output': ['NO\n']}, {'input': 'lkhrzDZmkdbjzYKPNMRkiwCFoZsMzBQMnxxdKKVJezSBjnLjPpUYtabcPTIaDJeDEobbWHdKOdVfMQwDXzDDcSrwVenDEYpMqfiOQ xSsqApWnAMoyhQXCKFzHvvzvUvkWwmwZrvZz\nsUzGspYpRFsHRbRgTQuCBgnFgPkisTUfFNwyEEWWRiweWWgjRkVQxgTwxOzdsOwfrGIH O gCXpzvHzfItuEHaihmugEyymSJIogYwX qAwcwIItidfnzZDhZgQHi eRjMAeVkJHceDZuJkmxGowOsmcGYYvk Ajtgi TxwihvjLViNZjvscTWvsaQUelTSivLShhEl\n', 'output': ['NO\n']}, {'input': 'BRsVjyNhrqRHVwrJzuzRigEhdpbDmaACSPfed\nlWqKTjlrqOCUbgBBZdZDGCeQJDXawPnnDkQdZDgwrEQk\n', 'output': ['NO\n']}, {'input': 'KRmINuyBYPwiTsdlyiNVuylToysJKmOpcLovAtwGPqrgFJQNAYvuAiyQRkeFMECVZvkDEmTauXlyjAaYRnTJXORMZRnTakBaUzSelMilejySDIZjQjzcOIrwXdvDvpeRIkoBgreyFXIyyIZutjiEBtwrmzQtPVUhvvdEtDMbXjBpoPVjGdM EXTAK JbCnw\nXZZqlJvzKKtvdNlzFPDTYxidqlsgufVzyEmO FZuLQ vVQsJESNviUCovCK NwwlbxsmPtOJNmAonCqrOZ bZ LVKAsQGmoLnYjeekvEIECFk\n', 'output': ['NO\n']}]


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <utility>
#include <stack>
#include <cstring>
#include <math.h>
#include<cstdio>
#include<deque>
#include<sstream>
#define mp make_pair
#define eps 1e-6
using namespace std;
int dx[] = { 0, 0, 1, -1, 1, 1, -1, -1 };
int dy[] = { 1, -1, 0, 0, 1, -1, 1, -1 };

int vis[111][111][111];
int vis2[111];
int main() {
    //freopen("A.txt", "rt", stdin);
    int n, m, a, b, k;
    scanf("%d%d%d", &n, &m, &k);
    int r = n * 2 + m * 2 -1;
    queue<pair < int , pair<int, int > > > q;
    for (int i = 0; i < k; i++){
        scanf("%d%d", &a, &b);
        q.push(mp ( i , (mp(a - 1, b - 1) )));
    }
    int lev = 0, f = 0;
    vector<int >res,res2;
    while (!q.empty()){
        int siz = q.size();

        while (siz--){
            int c = q.front().first;
            a = q.front().second.first;
            b = q.front().second.second;
            q.pop();

            if ((a == 0 && b == 0) || (a == n - 1 && b == m - 1) || (a == n - 1 && b == 0) || (a == 0 && b == m - 1)){
                //cout << lev << endl;
                res2.push_back(lev);
                continue;
            }
            if (a < 0 || b < 0 || a >= n || b >= m){
                //cout << lev << endl;
                if (!vis2[c])
                    res.push_back(lev);
                vis2[c] = 1;
                continue;
            }

            if (vis[a][b][c])
                continue;
            vis[a][b][c] = 1;

            for (int i = 0; i < 4; i++){
                int nx = a + dx[i];
                int ny = b + dy[i];
                q.push(mp(c,mp(nx, ny)));

            }
        }
        lev++;
    }
    int rr;
    if(res.size() )
        rr= r - res[0];
    if ((res2.size() && res2[0] <=5) || (res.size()  && res[0] <= 5))
        puts("YES");
    else
        puts("NO");
    return 0;
}

Volodya and Vlad play the following game. There are k pies at the cells of n×m board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.


#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long lld;
#define maxn 10000
lld dp[110][maxn];
int s[110];
lld dfs(int pos,lld now)
{
    if(now == 0)
        return 0;
    if(pos == -1)
        return now;
    if(now < maxn && dp[pos][now] != -1)
        return dp[pos][now];
    lld ret=dfs(pos-1,now)-dfs(pos-1,now/s[pos]);
    if(now < maxn)
        dp[pos][now]=ret;
    return ret;
}
int main()
{
    lld n;
    int k;
    cin >> n >> k;
    for(int i=0;i<k;i++)
        cin >> s[i];
    sort(s,s+k);
    memset(dp,-1,sizeof(dp));
    cout << dfs(k-1,n) << endl;
    return 0;
}

#include <map>
#include <set>
#include <cmath>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
#define li		long long
#define rep(i,to)	for(li i=0;i<((li)to);i++)
#define pb		push_back
#define sz(v)		((li)v.size())

#define MAX 300000
li dp[105][MAX];
li n,m;
li a[105];
li recur(li pos,li rem){
	if(rem==0) return rem;
	if(pos==m) return rem;
	if(MAX<=rem) return recur(pos+1,rem)-recur(pos+1,rem/a[pos]);
	li &res=dp[pos][rem];
	if(res!=-1) return res;
	return res=recur(pos+1,rem)-recur(pos+1,rem/a[pos]);
}

int main(){
	rep(i,105)rep(j,MAX) dp[i][j]=-1;
	cin>>n>>m;
	rep(i,m) cin>>a[i];
	sort(a,a+m);
	reverse(a,a+m);
	cout<<recur(0,n)<<endl;
}

Igor K. very much likes a multiplayer role playing game WineAge II. Who knows, perhaps, that might be the reason for his poor performance at the university. As any person who plays the game, he is interested in equipping his hero with as good weapon and outfit as possible. One day, as he was reading the game's forum yet again, he discovered a very interesting fact. As it turns out, each weapon in the game is characterised with k different numbers: a1,...,ak. They are called hit indicators and according to the game developers' plan they are pairwise coprime. The damage that is inflicted during a hit depends not only on the weapon's characteristics, but also on the hero's strength parameter. Thus, if the hero's strength equals n, than the inflicted damage will be calculated as the number of numbers on the segment , that aren't divisible by any hit indicator ai.Recently, having fulfilled another quest, Igor K. found a new Lostborn sword. He wants to know how much damage he will inflict upon his enemies if he uses it.


#include <cstdio>
#include <algorithm>
#include <iostream>
#define M 900000
#define N 400000
#define oo 10000000

using namespace std;
typedef long long ll;

pair<int,int> u[6];

class S{
public:
    S *e, *d;
    int x, y;
    int tmp;
    pair<int,int> ms[3];

    void update(int a, int b, S* ee, S* dd){
        e = ee, d = dd;
        x = a, y = b;
        tmp = 0;
        ms[0].first = 0, ms[0].second = b-a+1;
        ms[1].first = oo, ms[1].second = 0;
        ms[2].first = oo, ms[2].second = 0;
    }

    void add(int a, int b, int v){
        if(a <= x && b >= y){
            ms[0].first += v;
            ms[1].first += v;
            ms[2].first += v;
            tmp += v;
        }else{
            if(tmp){
                e->add(e->x,e->y,tmp);
                d->add(d->x,d->y,tmp);
                tmp = 0;
            }
            if(a <= e->y) e->add(a,min(e->y,b),v);
            if(b >= d->x) d->add(max(a,d->x),b,v);

            u[0] = e->ms[0], u[1] = e->ms[1];
            u[2] = d->ms[0], u[3] = d->ms[1];
            u[4] = e->ms[2], u[5] = d->ms[2];
            sort(u,u+6);

            ms[0] = u[0];
            int cnt = 0;
            for(int i=1; i<6 && cnt < 3; i++){
                if(u[i].first == ms[cnt].first) ms[cnt].second += u[i].second;
                else if(cnt < 2) ms[++cnt] = u[i];
                else break;
            }
        }
    }
};

S ss[M];
int p[N];
int g[N];

int cnt;
S* build(int a, int b){
    S* s = &ss[cnt++];
    s->update(a,b,NULL,NULL);
    if(a!=b){
        s->e = build(a,(a+b)/2);
        s->d = build(((a+b)/2) + 1, b);
    }
    return s;
}

int main(){
    cnt = 0;

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

    S* root = build(1,n);
    root->add(1,1,1);
    ll resp = 0LL;
    for(int i=2; i<=n; i++){
        root->add(1,i,1);
        if(p[i] > 1 && g[p[i]-1] < i) root->add(1,g[p[i]-1],-1);
        if(p[i] < n && g[p[i]+1] < i) root->add(1,g[p[i]+1],-1);

        for(int j=0; j<3; j++){
            if(root->ms[j].first >= 1 && root->ms[j].first <= 2)
                resp = resp + root->ms[j].second;
        }
        resp--;
    }
    cout << resp << endl;
    return 0;
}

#include <cstdio>
#include <algorithm>
#include <iostream>
#define M 900000
#define N 400000
#define oo 10000000

using namespace std;
typedef long long ll;

pair<int,int> u[6];

class S{
public:
    S *e, *d;
    int x, y;
    int tmp;
    pair<int,int> ms[3];

    void update(int a, int b, S* ee, S* dd){
        e = ee, d = dd;
        x = a, y = b;
        tmp = 0;
        ms[0].first = 0, ms[0].second = b-a+1;
        ms[1].first = oo, ms[1].second = 0;
        ms[2].first = oo, ms[2].second = 0;
    }

    void add(int a, int b, int v){
        if(a <= x && b >= y){
            ms[0].first += v;
            ms[1].first += v;
            ms[2].first += v;
            tmp += v;
        }else{
            if(tmp){
                e->add(e->x,e->y,tmp);
                d->add(d->x,d->y,tmp);
                tmp = 0;
            }
            if(a <= e->y) e->add(a,min(e->y,b),v);
            if(b >= d->x) d->add(max(a,d->x),b,v);

            u[0] = e->ms[0], u[1] = e->ms[1];
            u[2] = d->ms[0], u[3] = d->ms[1];
            u[4] = e->ms[2], u[5] = d->ms[2];
            sort(u,u+6);

            ms[0] = u[0];
            int cnt = 0;
            for(int i=1; i<6 && cnt < 3; i++){
                if(u[i].first == ms[cnt].first) ms[cnt].second += u[i].second;
                else if(cnt == 0) ms[++cnt] = u[i];
                else if(cnt == 1) ms[++cnt] = u[i];
                else break;
            }
        }
    }
};

S ss[M];
int p[N];
int g[N];

int cnt;
S* build(int a, int b){
    S* s = &ss[cnt++];
    s->update(a,b,NULL,NULL);
    if(a!=b){
        s->e = build(a,(a+b)/2);
        s->d = build(((a+b)/2) + 1, b);
    }
    return s;
}

int main(){
    cnt = 0;

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

    S* root = build(1,n);
    root->add(1,1,1);
    ll resp = 0LL;
    for(int i=2; i<=n; i++){
        root->add(1,i,1);
        if(p[i] > 1 && g[p[i]-1] < i) root->add(1,g[p[i]-1],-1);
        if(p[i] < n && g[p[i]+1] < i) root->add(1,g[p[i]+1],-1);

        for(int j=0; j<3; j++){
            if(root->ms[j].first >= 1 && root->ms[j].first <= 2)
                resp = resp + root->ms[j].second;
        }
        //printf("   >> %d %d %d\n",root->ms[0].first,root->ms[1].first,root->ms[2].first);
        resp--;
        //cout << "  " << resp << endl;
    }
    cout << resp << endl;
    return 0;
}

Nick has some permutation consisting of p integers from 1 to n. A segment [l,r] (l≤r) is a set of elements pi satisfying l≤i≤r.Nick calls a pair of segments [a0,a1] and [b0,b1] (1≤a0≤a1<b0≤b1≤n) good if all their (a1-a0+b1-b0+2) elements, when sorted in ascending order, form an arithmetic progression with a difference of 1. That is, when they sorted in ascending order, the elements are in the form {x,x+1,x+2,...,x+m-1}, for some x and m.Your task is to find the number of distinct pairs of good segments in the given permutation. Two pairs of segments are considered distinct if the sets of elements contained in these pairs of segments are distinct. For example, any segment [l,r] (l<r) can be represented as a pair of segments, as [l,i] and [i+1,r] (l≤i≤r). As all these pairs consist of the same set of elements, they are considered identical.See the notes accompanying the sample tests for clarification.