Wilbur the pig now wants to play with strings. He has found an n by m table consisting only of the digits from 0 to 9 where the rows are numbered 1 to n and the columns are numbered 1 to m. Wilbur starts at some square and makes certain moves. If he is at square (x, y) and the digit d (0≤d≤9) is written at position (x, y), then he must move to the square (x+ad, y+bd), if that square lies within the table, and he stays in the square (x, y) otherwise. Before Wilbur makes a move, he can choose whether or not to write the digit written in this square on the white board. All digits written on the whiteboard form some string. Every time a new digit is written, it goes to the end of the current string.Wilbur has q strings that he is worried about. For each string si, Wilbur wants to know whether there exists a starting position (x, y) so that by making finitely many moves, Wilbur can end up with the string si written on the white board.

The first line of the input consists of three integers n, m, and q (1≤n,m,q≤200) — the dimensions of the table and the number of strings to process, respectively.
Each of the next n lines contains m digits from 0 and 9 giving the table itself.
Then follow 10 lines. The i-th of them contains the values ai-1 and bi-1 (-200≤ai,bi≤200), i.e. the vector that Wilbur uses to make a move from the square with a digit i-1 in it.
There are q lines that follow. The i-th of them will contain a string si consisting only of digits from 0 to 9. It is guaranteed that the total length of these q strings won't exceed 1000000.

For each of the q strings, print "YES" if Wilbur can choose x and y in order to finish with this string after some finite number of moves. If it's impossible, than print "NO" for the corresponding string.

In the first sample, there is a 1 by 1 table consisting of the only digit 0. The only move that can be made is staying on the square. The first string can be written on the white board by writing 0 repeatedly. The second string cannot be written as there is no 2 on the table.

#include<stdio.h>
#include<string.h>
int n,m,q,ip1[200][200],procinfo[40000][10],status[200][200],ip2[10][2],glob[10],nm;
char ch[201],inch[1000001];

void fill_glob(int si,int sj,int ei,int ej){

int i,dx,dy;
for(i=0;i<10;i++)
    glob[i]=-1;

while(!(si==ei && sj == ej)){
if(glob[ip1[si][sj]]==-1)
    glob[ip1[si][sj]]=si*m+sj;

dx=ip2[ip1[si][sj]][0];
dy=ip2[ip1[si][sj]][1];

si=si+dx;
sj=sj+dy;

}

if(glob[ip1[si][sj]]==-1)
    glob[ip1[si][sj]]=si*m+sj;

//test
/*printf("%d %d %d %d\n",si,sj,ei,ej);
for(i=0;i<10;i++)
    printf("%d ",glob[i]);
printf("\n");*/

}

void process_indx(int i,int j){

status[i][j]=-2;
int ni,nj,dx,dy,eq,l,neq;
eq=i*m+j;
dx=ip2[ip1[i][j]][0];
dy=ip2[ip1[i][j]][1];
ni=i+dx;
nj=j+dy;
neq=ni*m+nj;

if(ni<0 || ni>n-1 || nj <0 || nj >m-1){
for(l=0;l<10;l++)
    procinfo[eq][l]=-1;
    procinfo[eq][ip1[i][j]]=eq;
status[i][j]=0;
return;
}

if(status[ni][nj]==-2){

fill_glob(ni,nj,i,j);
for(l=0;l<10;l++)
    procinfo[eq][l]=glob[l];
status[i][j]=0;
return;
}

if(status[ni][nj]==-1){

    process_indx(ni,nj);

}

    for(l=0;l<10;l++)
    procinfo[eq][l]=procinfo[neq][l];
    procinfo[eq][ip1[ni][nj]]=neq;
    status[i][j]=0;
    return;

}

void read_input(){
int i,j;
scanf("%d %d %d",&n,&m,&q);
for(i=0;i<n;i++){
   scanf("%s",ch);
    for(j=0;j<m;j++){
        ip1[i][j]=ch[j]-'0';
        status[i][j]=-1;
    }
}
for(i=0;i<10;i++)
    scanf("%d %d",&ip2[i][0],&ip2[i][1]);

nm=n*m;
}

void process_info(){
int i,j;
for(i=0;i<n;i++)
    for(j=0;j<m;j++)
     {
          if(status[i][j]==0)
            continue;
          process_indx(i,j);
     }

//test

/*for(i=0;i<n*m;i++){
    for(j=0;j<10;j++)
    printf("%d ",procinfo[i][j]);
printf("\n");

}*/

}

int main(){
int i,len,j,x,y,k,curindx;
read_input();
process_info();

for(i=0;i<q;i++){
scanf("%s",inch);
len=strlen(inch);
for(j=0;j<n;j++)
    for(k=0;k<m;k++)
       status[j][k]=-1;
for(j=0;j<nm;j++){
    x=j/m;
    y=j-x*m;
    if(ip1[x][y]!=inch[0]-'0')
        continue;
    if(status[x][y]!=-1)
        continue;
    status[x][y]=0;
    curindx=j;
    for(k=1;k<len;k++){
       curindx=procinfo[curindx][inch[k]-'0'];
       if(curindx==-1)
         break;
       x=curindx/m;
       y=curindx-x*m;
       if(status[x][y]!=-1 && status[x][y] >=k)
        break;
       status[x][y]=k;
   }

    if(k==len)
        break;

}

if(j<nm)
    printf("YES\n");
else
    printf("NO\n");

}
return 0;

}


Æsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers ($$$1, 2, 3, \ldots$$$). The node with a number $$$x$$$ ($$$x > 1$$$), is directly connected with a node with number $$$\frac{x}{f(x)}$$$, with $$$f(x)$$$ being the lowest prime divisor of $$$x$$$.Vanessa's mind is divided into $$$n$$$ fragments. Due to more than 500 years of coma, the fragments have been scattered: the $$$i$$$-th fragment is now located at the node with a number $$$k_i!$$$ (a factorial of $$$k_i$$$).To maximize the chance of successful awakening, Ivy decides to place the samples in a node $$$P$$$, so that the total length of paths from each fragment to $$$P$$$ is smallest possible. If there are multiple fragments located at the same node, the path from that node to $$$P$$$ needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node $$$P$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — number of fragments of Vanessa's mind. The second line contains $$$n$$$ integers: $$$k_1, k_2, \ldots, k_n$$$ ($$$0 \le k_i \le 5000$$$), denoting the nodes where fragments of Vanessa's mind are located: the $$$i$$$-th fragment is at the node with a number $$$k_i!$$$.

Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node $$$P$$$). As a reminder, if there are multiple fragments at the same node, the distance from that node to $$$P$$$ needs to be counted multiple times as well.

NoteConsidering the first $$$24$$$ nodes of the system, the node network will look as follows (the nodes $$$1!$$$, $$$2!$$$, $$$3!$$$, $$$4!$$$ are drawn bold):For the first example, Ivy will place the emotion samples at the node $$$1$$$. From here:  The distance from Vanessa's first fragment to the node $$$1$$$ is $$$1$$$.  The distance from Vanessa's second fragment to the node $$$1$$$ is $$$0$$$.  The distance from Vanessa's third fragment to the node $$$1$$$ is $$$4$$$. The total length is $$$5$$$.For the second example, the assembly node will be $$$6$$$. From here:  The distance from Vanessa's first fragment to the node $$$6$$$ is $$$0$$$.  The distance from Vanessa's second fragment to the node $$$6$$$ is $$$2$$$.  The distance from Vanessa's third fragment to the node $$$6$$$ is $$$2$$$.  The distance from Vanessa's fourth fragment to the node $$$6$$$ is again $$$2$$$. The total path length is $$$6$$$.

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

#define A	5000
#define N_	(A * 3)
#define INF	0x3f3f3f3f3f3f3f3fLL

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

int oo[1 + (N_ - 1) * 2], oj[1 + (N_ - 1) * 2];

int link(int o, int j) {
	static int _ = 1;

	oo[_] = o, oj[_] = j;
	return _++;
}

int count(int n, int p) {
	return n < p ? 0 : n / p + count(n / p, p);
}

int ae[N_], pp[N_], dd[N_], sz[N_], ii[A + 1], n;

void init() {
	static char composite[A + 1];
	static int primes[A + 1];
	int n_, a, b, cnt, i, j;

	for (a = 2; a <= A / a; a++) {
		if (composite[a])
			continue;
		for (b = a * a; b <= A; b += a)
			composite[b] = 1;
	}
	cnt = 0;
	for (a = 2; a <= A; a++)
		if (!composite[a])
			primes[cnt++] = a;
	n_ = 0;
	pp[n_] = -1, dd[n_] = 0;
	ii[1] = n_++;
	for (a = 2; a <= A; a++) {
		int h, d, d_;

		d = 0;
		for (h = 0; h < cnt; h++)
			d += count(a, primes[h]);
		d_ = 0;
		for (h = cnt - 1; h >= 0; h--) {
			d_ += count(a - 1, primes[h]);
			if (a % primes[h] == 0)
				break;
		}
		i = ii[a - 1], j = -1;
		while (1)
			if (dd[i] > d_)
				j = i, i = pp[i];
			else if (dd[i] == d_) {
				pp[n_] = i, dd[n_] = d, n_++;
				ii[a] = n_ - 1;
				break;
			} else {
				int k = n_++;

				pp[k] = i, dd[k] = d_;
				if (j != -1)
					pp[j] = k;
				pp[n_] = k, dd[n_] = d, n_++;
				ii[a] = n_ - 1;
				break;
			}
	}
	for (j = 1; j < n_; j++) {
		i = pp[j];
		ae[i] = link(ae[i], j), ae[j] = link(ae[j], i);
	}
}

long long dfs1(int p, int i) {
	int o;
	long long x;

	x = (long long) sz[i] * dd[i];
	for (o = ae[i]; o; o = oo[o]) {
		int j = oj[o];

		if (j != p) {
			x += dfs1(i, j);
			sz[i] += sz[j];
		}
	}
	return x;
}

long long ans;

void dfs2(int p, int i, long long x) {
	int o;

	ans = min(ans, x);
	for (o = ae[i]; o; o = oo[o]) {
		int j = oj[o];

		if (j != p) {
			int w = abs(dd[i] - dd[j]);

			dfs2(i, j, x - (long long) sz[j] * w + (long long) (n - sz[j]) * w);
		}
	}
}

int main() {
	int i;

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

		scanf("%d", &a);
		sz[ii[a > 0 ? a : 1]]++;
	}
	ans = INF;
	dfs2(-1, 0, dfs1(-1, 0));
	printf("%lld\n", ans);
	return 0;
}


There are n students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the i-th student ai minutes to finish his/her independent piece.If students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum ai in the group minus the minimum ai in the group. Note that a group containing a single student has an imbalance of 0. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most k?Two divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.

The first line contains two space-separated integers n and k (1 ≤ n ≤ 200, 0 ≤ k ≤ 1000) — the number of students and the maximum total imbalance allowed, respectively. The second line contains n space-separated integers ai (1 ≤ ai ≤ 500) — the time it takes the i-th student to complete his/her independent piece of work.

Print a single integer, the number of ways the students can form groups. As the answer may be large, print its value modulo 109 + 7.

NoteIn the first sample, we have three options:   The first and second students form a group, and the third student forms a group. Total imbalance is 2 + 0 = 2.  The first student forms a group, and the second and third students form a group. Total imbalance is 0 + 1 = 1.  All three students form their own groups. Total imbalance is 0. In the third sample, the total imbalance must be 0, so each student must work individually.

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

typedef long long LL;

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

int a[200], n, k;
LL dp[2][201][1001];
const LL mod=1000000007;

LL get(int i, int num, int s){
	if(s>k || num<0) return 0;
	return dp[i&1][num][s];
}

int main(){
	int i, j, l, add;
	scanf("%d %d", &n, &k);
	for(i=0;i<n;++i) scanf("%d", a+i);
	for(i=0;i<=k;++i) dp[n&1][0][i]=1;
	for(i=1;i<=n;++i) for(j=0;j<=k;++j) dp[n&1][i][j]=0;
	qsort(a, n, sizeof(int), comp);
	for(i=n-1;i>0;--i){
		for(j=0;j<=n;++j){
			add=j*(a[i]-a[i-1]);
			for(l=0;l<=k;++l){
				dp[i&1][j][l]=(get(i+1, j+1, l+add)+j*get(i+1, j-1, l+add)+
						(j+1)*get(i+1, j, l+add))%mod;
			}
		}
	}
	printf("%I64d\n", (get(1, 1, 0)+get(1, 0, 0))%mod);
	return 0;
}


Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.

The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square.

Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7).

NoteIn the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.


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.

A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.

On a single line print the answer to the problem. If such number does not exist, then you should print -1.

NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.


One day as Petya and his friend Vasya were having one of their numerous trips, they decided to visit a museum castle. The museum has a specific shape: it consists of n rooms connected with m corridors so that one can access any room from any other one.After the two friends had a little walk around the museum, they decided to split and watch the pieces of art each of them found interesting. They agreed to meet in one of the rooms at six p.m. However, they forgot one quite essential thing: they didn't specify the place to meet and when the time came, they started to rush about the museum looking for each other (they couldn't call each other as roaming made a call's cost skyrocket).Yet, even despite the whole rush, they couldn't get enough of the pieces of art, that's why each of them has the following strategy: each minute he make a decision where to go — with probability pi he doesn't move to any other place during this minute (i.e. he stays in the room). With probability 1 - pi he equiprobably choose one of the adjacent rooms and went there along the corridor. Here i is the ordinal number of the current room. Building was expensive in ancient times, that's why each corridor connected two different rooms, and any two rooms had no more than one corridor between them. The boys act simultaneously. As the corridors are dark, it is impossible to meet there; however, one can walk along the corridors in both directions (besides, the two boys can be going through the same corridor simultaneously without meeting). The boys act like that until they meet each other. More formally, the two friends meet when at some moment of time both of them decided to appear in the same room.For each room find the probability that the boys will meet there considering that at 6 p.m. they are positioned in rooms a and b correspondingly.

The first line contains four integers: n (1 ≤ n ≤ 22), representing the numbers of rooms; m , representing the number of corridors; a, b (1 ≤ a, b ≤ n), representing the numbers of Petya's and Vasya's starting rooms correspondingly. Next m lines contain pairs of numbers — the numbers of rooms connected by a corridor. Next n lines contain probabilities pi (0.01 ≤ pi ≤ 0.99) with the accuracy of up to four digits after the decimal point — the probability to stay in room i. It is guaranteed that every room can be reached from every other room by corridors.

In the only line print n space-separated numbers, the i-th number should represent the probability that the friends meet in the i-th room with absolute or relative error of no more than 10 - 6.

NoteIn the first sample the museum is symmetric. That means the probabilities to meet in rooms 1 and 2 are equal. And their sum equals to one. So, each probability equals 0.5.


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.

The first line contains two integers n and k (1 ≤ n ≤ 2500, 1 ≤ k ≤ 5) — the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.

Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.

NoteIn the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".

2 1
day
may
sun
fun
test
hill
fest
thrill

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


Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number n.There are m buses running between the house and the school: the i-th bus goes from stop si to ti (si < ti), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the i-th bus on any stop numbered from si to ti - 1 inclusive, but he can get off the i-th bus only on the bus stop ti.Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house.Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109 + 7).

The first line contains two space-separated integers: n and m (1 ≤ n ≤ 109, 0 ≤ m ≤ 105). Then follow m lines each containing two integers si, ti. They are the numbers of starting stops and end stops of the buses (0 ≤ si < ti ≤ n).

Print the only number — the number of ways to get to the school modulo 1000000007 (109 + 7).

NoteThe first test has the only variant to get to school: first on bus number one to the bus stop number one; then on bus number two to the bus stop number two.In the second test no bus goes to the third bus stop, where the school is positioned. Thus, the correct answer is 0.In the third test Gerald can either get or not on any of the first four buses to get closer to the school. Thus, the correct answer is 24 = 16.


As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC). A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to different departments. There are m departments in GUC, numbered from 1 to m. Herr Wafa's department has number h. For each department i, Herr Wafa knows number si — how many students who play basketball belong to this department.Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department. Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other.

The first line contains three integers n, m and h (1 ≤ n ≤ 100, 1 ≤ m ≤ 1000, 1 ≤ h ≤ m) — the number of players on the team, the number of departments in GUC and Herr Wafa's department, correspondingly.  The second line contains a single-space-separated list of m integers si (1 ≤ si ≤ 100), denoting the number of students in the i-th department. Note that sh includes Herr Wafa.

Print the probability that Herr Wafa will have at least one teammate from his department. If there is not enough basketball players in GUC to participate in ABC, print -1. The answer will be accepted if it has absolute or relative error not exceeding 10 - 6.

NoteIn the first example all 3 players (2 from department 1 and 1 from department 2) must be chosen for the team. Both players from Wafa's departments will be chosen, so he's guaranteed to have a teammate from his department.In the second example, there are not enough players.In the third example, there are three possibilities to compose the team containing Herr Wafa. In two of them the other player from Herr Wafa's department is part of the team.

#include<stdio.h>
int main()
{
	int j,i,n,m,h,temp,a,b,ans1,ans2;
	double ans;
	scanf("%d%d%d",&n,&m,&h);
	b=0;
	for(i=1;i<=m;i++)
	{
		scanf("%d",&temp);
		if(i==h)
			a=temp-1;
		else
			b+=temp;
	}
	ans=1;
	n--;
	/*for(i=1,j=a;i<=a;i++,j--)
	{
		if(i<n+1)
			ans*=(long double)(b-n+i);
		if(j>a-n)
			ans/=(long double)(b+j);
	}*/
	for(i=0;i<n;i++)
	{
		ans1=(b-i);
		ans2=(b+a-i);
		ans*=(double)ans1/(double)ans2;
	}
	if(a+b<n)
		ans=2;
	ans=1.0-ans;
	printf("%lf\n",ans);
	return 0;
}


Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains  distinct theorems. Besides, no theorem is mentioned in more than one card (that is,  theorems won't be mentioned in any card). During the exam several students may get the same card.We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 100) — the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 ≤ ai ≤ 100), the i-th number (1 ≤ i ≤ n) corresponds to Vasya's proficiency in the i-th theorem. The third line contains number q (0 ≤ q ≤ 100) — the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card:  integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).

Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.

NoteLet's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).The ⌊ x⌋ operation denotes taking integer part of real number x (rounding down).

/*  problem B */

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

int find(int base[][100], int  key[], int num,int k)
 {

 int i,j,flag=0;

 i=1;
 if(k>=0)
 for(i=0;i<=k;i++){

  for(j=0;j<num;j++){
  if(key[0]==base[i][j])
  {
  flag=1; /*found */
  break;
  }
 }
 if(flag==1) break;

 }

 if(i>k && !flag)
  {
   k++;
   for(j=0;j<num;j++)
   base[k][j]=key[j];
  }

  return k;

}

int intcomp(const void *p1,const void * p2)
{

return (*(int *)p1-*(int *)p2);

}

int sum_kmin(int * aux, int k,int length)
 {

 int i,sum=0;
 for(i=0;i<k;i++)
  sum+=aux[i];

 return sum;
 }

int sum_kmax(int * aux, int k, int length)
 {

 int i, sum=0;
 for(i=0;i<k;i++)
  sum+=aux[length-1-i];

 return sum;

 }

int min(int *aux, int length)
 {
 int i=0,min=aux[0];
 for(i=1;i<length;i++)
  if(aux[i]<min) min=aux[i];

 return min;

 }

int max(int * aux, int length)
 {

 int i=0,max=aux[0];
 for(i=1;i<length;i++)
  if(aux[i]>max) max=aux[i];

 return max;
 }

int main(void)
{

int marks[100][2]; 									/* vasya's marks */
int aux[100],maux[100],l;

int k,n,q,num,i,j,current=-1,length,sum,before;
double avg;
int cards[100][100];

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

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

num=n/k;
scanf("%d",&q);

l=0;
for(i=0;i<q;i++)
 {
 sum=0;
 for(j=0;j<num;j++){
 scanf("%d",&aux[j]);
 marks[aux[j]-1][1]=1;
 sum+=marks[aux[j]-1][0];
 }

 before=current;
current=find(cards,aux,num,current);
if(before!=current) maux[l++]=sum;
 }

j=0;
if(current<k-1)
for(i=0;i<n;i++)
{
if(marks[i][1]==0) { aux[j++]=marks[i][0];}
}

qsort(aux,j,sizeof(int),intcomp);
length=j;

/*for(i=0;i<=current;i++){
 printf("\n");
 for(j=0;j<num;j++)
  printf("  %d",cards[i][j]);

 }*/

if(j){
maux[l++]=sum_kmin(aux,num,length);
maux[l++]=sum_kmax(aux,num,length);
}

avg=(double)min(maux,l)/num;
printf("%.10lf ",avg);
avg=(double)max(maux,l)/num;
printf("%.10lf ",avg);

return 0;
}


Piet is one of the most known visual esoteric programming languages. The programs in Piet are constructed from colorful blocks of pixels and interpreted using pretty complicated rules. In this problem we will use a subset of Piet language with simplified rules.The program will be a rectangular image consisting of colored and black pixels. The color of each pixel will be given by an integer number between 0 and 9, inclusive, with 0 denoting black. A block of pixels is defined as a rectangle of pixels of the same color (not black). It is guaranteed that all connected groups of colored pixels of the same color will form rectangular blocks. Groups of black pixels can form arbitrary shapes.The program is interpreted using movement of instruction pointer (IP) which consists of three parts: current block pointer (BP); note that there is no concept of current pixel within the block; direction pointer (DP) which can point left, right, up or down; block chooser (CP) which can point to the left or to the right from the direction given by DP; in absolute values CP can differ from DP by 90 degrees counterclockwise or clockwise, respectively.Initially BP points to the block which contains the top-left corner of the program, DP points to the right, and CP points to the left (see the orange square on the image below).One step of program interpretation changes the state of IP in a following way. The interpreter finds the furthest edge of the current color block in the direction of the DP. From all pixels that form this edge, the interpreter selects the furthest one in the direction of CP. After this, BP attempts to move from this pixel into the next one in the direction of DP. If the next pixel belongs to a colored block, this block becomes the current one, and two other parts of IP stay the same. It the next pixel is black or outside of the program, BP stays the same but two other parts of IP change. If CP was pointing to the left, now it points to the right, and DP stays the same. If CP was pointing to the right, now it points to the left, and DP is rotated 90 degrees clockwise.This way BP will never point to a black block (it is guaranteed that top-left pixel of the program will not be black).You are given a Piet program. You have to figure out which block of the program will be current after n steps.

The first line of the input contains two integer numbers m (1 ≤ m ≤ 50) and n (1 ≤ n ≤ 5·107). Next m lines contain the rows of the program. All the lines have the same length between 1 and 50 pixels, and consist of characters 0-9. The first character of the first line will not be equal to 0.

Output the color of the block which will be current after n steps of program interpretation.

NoteIn the first example IP changes in the following way. After step 1 block 2 becomes current one and stays it after two more steps. After step 4 BP moves to block 3, after step 7 — to block 4, and finally after step 10 BP returns to block 1.  The sequence of states of IP is shown on the image: the arrows are traversed clockwise, the main arrow shows direction of DP, the side one — the direction of CP.

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

char field[55][55];
int n, steps, m;
int next[55][55][4][2][4];

int main() {
    int i, j, k, dir, r;
    scanf("%d %d", &n, &steps);
    for(i = 0; i < n; i++)
        scanf("%s", field[i]);
    m = strlen(field[0]);

    for(i = 0; i < n; i++)
        for(j = 0; j < m; j++)
            for(k = 0; k < 4; k++)
                for(dir = 0; dir < 2; dir++)
                    for(r = 0; r < 4; r++)
                        next[i][j][k][dir][r] = -1;

    for(i = 0; i < n; i++)
        for(j = 0; j < m; j++) {
            if(field[i][j] != '0') {
                int left, right, top, bottom;
                left = right = j;
                top = bottom = i;
                while(left > 0 && field[i][left - 1] == field[i][j])
                    left--;
                while(right < m - 1 && field[i][right + 1] == field[i][j])
                    right++;
                while(top > 0 && field[top - 1][j] == field[i][j])
                    top--;
                while(bottom < n - 1 && field[bottom + 1][j] == field[i][j])
                    bottom++;

                for(k = 0; k < 4; k++) {
                    for(dir = 0; dir < 2; dir++) {
                        int nx, ny;
                        if(k == 0) {
                            nx = top - 1;
                            ny = (1 - dir ? left : right);
                        } else if(k == 1) {
                            ny = right + 1;
                            nx = (1 - dir ? top : bottom);
                        } else if(k == 2) {
                            nx = bottom + 1;
                            ny = (1 - dir ? right : left);
                        } else {
                            ny = left - 1;
                            nx = (1 - dir ? bottom : top);
                        }
                        if(nx < 0 || ny < 0 || nx >= n || ny >= m
                                || field[nx][ny] == '0') {
                            next[i][j][k][dir][0] = i;
                            next[i][j][k][dir][1] = j;
                            next[i][j][k][dir][2] = (k + dir) % 4;
                            next[i][j][k][dir][3] = 1 - dir;
                            continue;
                        }

                        next[i][j][k][dir][0] = nx;
                        next[i][j][k][dir][1] = ny;
                        next[i][j][k][dir][2] = k;
                        next[i][j][k][dir][3] = dir;
                    }
                }
            }
        }
    int cx = 0, cy = 0, ck = 1, cdir = 0;
    for(i = 0; i < steps; i++) {
        int tx, ty, tk, tdir;
        tx = cx; ty = cy; tk = ck; tdir = cdir;

        cx = next[tx][ty][tk][tdir][0];
        cy = next[tx][ty][tk][tdir][1];
        ck = next[tx][ty][tk][tdir][2];
        cdir = next[tx][ty][tk][tdir][3];

    }
    printf("%c\n", field[cx][cy]);
    return 0;
}


You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.

The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.

Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).

#include <stdio.h>

#define MAXN 100010
#define EPS 1e-6
#define DIMS 2

int N,M;

double A[MAXN][2];
double B[MAXN][2];

double cross(double *a,double *b)
{
    return (a[0])*(b[1])-(a[1])*(b[0]);
}

void sub(double *res,double *a,double *b)
{
    int i;
    for(i=0;i<DIMS;i++)
        res[i]=a[i]-b[i];
}

double abso(double a)
{
    return (a<0)?-a:a;
}

char verify(int index,int i,int j)
{
    double edge[2];
    double point[2];
    sub(edge,A[j],A[i]);
    sub(point,B[index],A[i]);
    if (cross(point,edge)>EPS)
        return 1;
    else
        return 0;
}

char binary_search(int index)
{
    double b[2];
    double m_b[2];
    double m[2];
    double m_a[2];
    sub(b,B[index],A[0]);
    int mid;
    int lo=1,hi=N-1;
    while(lo<=hi)
    {
        mid=lo + (hi-lo)/2;
        sub(m,A[mid],A[0]);
        if (mid>0)
        {
            sub(m_b,A[mid-1],A[0]);
            if(abso(cross(b,m))<EPS || abso(cross(b,m_b))<EPS || (cross(b,m)*cross(b,m_b))<0)
            {
                if (!verify(index,mid-1,mid))
                    return 0;
                else
                    return 1;
            }
        }
        if (mid<N-1)
        {
            sub(m_a,A[mid+1],A[0]);
            if(abso(cross(b,m))<EPS || abso(cross(b,m_a))<EPS || (cross(b,m)*cross(b,m_a))<0)
            {
                if (!verify(index,mid,mid+1))
                    return 0;
                else
                    return 1;
            }
        }
        if (cross(b,m)<0)
            hi=mid-1;
        else
            lo=mid+1;
    }
    /*error*/
    return -1;
}

int main()
{
    int i;
    scanf("%d",&N);
    for(i=0;i<N;i++)
        scanf("%lf %lf",&A[i][0],&A[i][1]);
    scanf("%d",&M);
    for(i=0;i<M;i++)
        scanf("%lf %lf",&B[i][0],&B[i][1]);
    double tmp[2];
    double f[2];
    double s[2];
    char flag=0;
    for(i=0;i<M;i++)
    {
        sub(tmp,B[i],A[0]);
        sub(f,A[1],A[0]);
        sub(s,A[N-1],A[0]);
        if (cross(tmp,f)<EPS)
        {
            flag=1;
            break;
        }
        if (cross(tmp,s)>-EPS)
        {
            flag=1;
            break;
        }
        if (!binary_search(i))
        {
            flag=1;
            break;
        }
    }
    if (flag)
        printf("NO\n");
    else
        printf("YES\n");
    return 0;
}


There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

The first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

#include <stdbool.h>
#include "stdio.h"
#include "stdint.h"
#include "string.h"
#include "stdlib.h"

#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define N 100000
int n, k, a[N], b[N];
int mil, mii, mi[N], mal, mai, ma[N];

int main() {
    scanf("%d %d", &n, &k);
    int ans = 0, ansb = 0;
    for (int i=0,l=0; i<n; i++) {
        scanf("%d", &a[i]);
        while (mil && a[i] <= a[mi[mil-1]]) mil--;
        mi[mil++] = i;
        while (mal && a[i] >= a[ma[mal-1]]) mal--;
        ma[mal++] = i;

        mii = min(mii, mil-1);
        mai = min(mai, mal-1);
        while (a[ma[mai]]-a[mi[mii]] > k) {
            l++;
            if (l > ma[mai]) mai++;
            if (l > mi[mii]) mii++;
        }
        b[i] = l;
        ans = max(ans, i-l);
        /*
        printf("min: %d\n", mii);
        for (int j=0; j<mil; j++) printf("%d ", a[mi[j]]);
        printf("\nmax %d\n", mai);
        for (int j=0; j<mal; j++) printf("%d ", a[ma[j]]);
        printf("\n");
        printf("%d %d %d\n\n", l, i, a[ma[mai]] - a[mi[mii]]);
         */
    }
    for (int i=0; i<n; i++) ansb += (i-b[i] == ans);
    printf("%d %d\n", ans+1, ansb);
    for (int i=0; i<n; i++) {
        if (i-b[i] == ans) {
            printf("%d %d\n", b[i]+1, i+1);
        }
    }
}


Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:#define macro_name macro_valueAfter the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.One of the main problems arising while using macros — the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.Let's consider the following example. Say, we declared such a #define construction:#define sum x + yand further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise — suspicious.Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".

The first line contains the only number n (0 ≤ n ≤ 100) — the amount of #define constructions in the given program. Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax: #define name expression where   name — the macro name,  expression — the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.  All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction. Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions. The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol. The length of any line from the input file does not exceed 100 characters.

Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".

4
#define sum  x + y
#define mul  a * b
#define div  a / b
#define expr sum + mul * div * mul
expr

3
#define SumSafe   (a+b)
#define DivUnsafe  a/b
#define DenominatorUnsafe  a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)

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

#define N	100
#define M	100000

void trim(char *s) {
	static char t[128];
	int n, m, i;

	memset(t, 0, sizeof t);
	n = strlen(s);
	for (i = 0, m = 0; i < n; i++)
		if (!isspace(s[i]))
			t[m++] = s[i];
	strcpy(s, t);
}

int isop(char c) {
	return c == '[' || c == ']' || c == '(' || c == ')' || c == '+' || c == '-' || c == '*' || c == '/';
}

int xx[M], yy[M];

int replace(char *ss, char *s, char *t, int x) {
	static char s_[M + 1];
	int n, m, l, n_, i, change;

	n = strlen(ss);
	m = strlen(s);
	l = strlen(t);
	memset(s_, 0, sizeof s_);
	n_ = 0;
	change = 0;
	memset(xx, 0, sizeof xx);
	for (i = 0; i < n; )
		if (i + m <= n && strncmp(ss + i, s, m) == 0 && (i == 0 || isop(ss[i - 1])) && (i + m == n || isop(ss[i + m]))) {
			xx[n_] = x;
			s_[n_++] = '[';
			memcpy(s_ + n_, t, l);
			n_ += l;
			s_[n_++] = ']';
			i += m;
			change = 1;
		} else {
			xx[n_] = yy[i];
			s_[n_++] = ss[i++];
		}
	strcpy(ss, s_);
	memset(yy, 0, sizeof yy);
	memcpy(yy, xx, n_ * sizeof *xx);
	return change;
}

static char t1[N][128], t2[N][128];
static char aa[N + 1], bb[N + 1], cc[N + 1];
int n;

void parse(char *ss, int x) {
	static int stack[M];
	int m, i, j, j_, x_, cnt, cnt_;

	aa[x] = 1;
	memset(yy, 0, sizeof yy);
	for (i = 0; i < x; i++)
		if (replace(ss, t1[i], t2[i], i) && !aa[i]) {
			aa[x] = bb[x] = cc[x] = 0;
			return;
		}
	bb[x] = cc[x] = 0;
	m = strlen(ss);
	for (j = 0, cnt = 0, cnt_ = 0; j < m; j++) {
		if (ss[j] == '[')
			stack[cnt++] = j;
		else if (ss[j] == ']') {
			j_ = stack[--cnt], x_ = xx[j_];
			if (j_ > 0) {
				if ((ss[j_ - 1] == '*' || ss[j_ - 1] == '/') && bb[x_]) {
					aa[x] = bb[x] = cc[x] = 0;
					return;
				}
				if (ss[j_ - 1] == '-' && bb[x_]) {
					aa[x] = bb[x] = cc[x] = 0;
					return;
				}
				if (ss[j_ - 1] == '/' && cc[x_]) {
					aa[x] = bb[x] = cc[x] = 0;
					return;
				}
			}
			if (j + 1 < m && (ss[j + 1] == '*' || ss[j + 1] == '/') && bb[x_]) {
				aa[x] = bb[x] = cc[x] = 0;
				return;
			}
			if (bb[x_] && cnt_ == 0)
				bb[x] = 1;
			if (cc[x_] && cnt_ == 0)
				cc[x] = 1;
		}
		if ((ss[j] == '+' || ss[j] == '-') && cnt_ == 0)
			bb[x] = 1;
		else if ((ss[j] == '*' || ss[j] == '/') && cnt_ == 0)
			cc[x] = 1;
		if (ss[j] == '(')
			cnt_++;
		else if (ss[j] == ')')
			cnt_--;
	}
}

int main() {
	static char ss[M + 2], tt[M + 2], s[128];
	int i, len;

	scanf("%d", &n);
	for (i = 0; i < n; i++) {
		len = 0;
		while (len < 7) {
			scanf("%s", s);
			len += strlen(s);
		}
		scanf("%s", t1[i]);
		fgets(t2[i], 128, stdin);
		trim(t2[i]);
	}
	fgets(ss, M + 2, stdin);
	trim(ss);
	for (i = 0; i <= n; i++) {
		strcpy(tt, i < n ? t2[i] : ss);
		parse(tt, i);
	}
	printf(aa[n] ? "OK\n" : "Suspicious\n");
	return 0;
}

[{'input': '1\r\n#define sum x + y\r\n1 * sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum  (x + y)\r\nsum - sum\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define sum  x + y\r\n#define mul  a * b\r\n#define div  a / b\r\n#define expr sum + mul * div * mul\r\nexpr\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define SumSafe   (a+b)\r\n#define DivUnsafe  a/b\r\n#define DenominatorUnsafe  a*b\r\n((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)\r\n', 'output': ['Suspicious\r\n']}, {'input': '0\r\naa + b - c * (ddd * eee / fff * a / b * c + d - b + c - (a + b)) - d\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n#define a b\r\n#define c d\r\na + b + c + d + 1234567 -10*(2-2+1000*1000*1000*1000*1000)\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n  #  define  macros    (  x  +  y  ) \r\n # define  Macros (x+y)\r\nmacros/Macros\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n#define A v\r\n#define a v/v/v\r\nv/A\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n#define A v\r\n#define a v/v/v\r\nv/a\r\n', 'output': ['Suspicious\r\n']}, {'input': '2\r\n#define A v\r\n#define a v/v/v\r\nv/(a)\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define a x*y\r\nc/a\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define a b*c\r\na/a*a\r\n', 'output': ['Suspicious\r\n']}, {'input': '3\r\n#define mul  x*y\r\n#define bad  x/mul\r\n#define good x/(mul)\r\ngood\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define mult   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nsum+difference+(sum)*(difference)-mult+mult*division+division*mult+division/(mult+sum-(difference))\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(difference/division)+sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(difference)*sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(sum)/multiplication\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nsum/(multiplication)\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n#define res (0-difference)\r\nsum+res*multiplication\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\ndivision/(multiplication/(division)/DIVISION/(sum-division-multiplication-(difference)))\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define sum  x + y\r\n#define SomeBad  (2 * sum)\r\n#define SomePossiblyGood  0 * SomeBad + (x + x - 2*x) * SomeBad\r\nSomePossiblyGood\r\n', 'output': ['Suspicious\r\n']}, {'input': '2\r\n#define a  0\r\n#define b  (a-a)*(x/x-1)\r\nb-b/b*b\r\n', 'output': ['Suspicious\r\n']}, {'input': '2\r\n#define fkdsjfslkjfsdk x/0\r\n#define fkdsjfslkjfsdksdds 0/(0-0)\r\nfkdsjfslkjfsdk + fkdsjfslkjfsdks + fkdsjfslkjfsdkssds\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define null x/0\r\n#define some x/x\r\n#define bad 1/x\r\nbad/0+0/bad+0/0*bad\r\n', 'output': ['Suspicious\r\n']}, {'input': '3\r\n#define MWjGY x+x*53 *x\r\n#define ovqZ 2/926+x/A\r\n#define uU 55-qRj*A*2\r\nx*A/x-A\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define zz 5+7/x*x*9\r\n#define mlTL 6+x/7+x/x\r\n#define DUO 7*7-x+zz\r\n#define IH 6*4-x+x\r\n67/(5)-IH\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define Oc 9/51+65+vN\r\n#define gga 53/ 94/x/x\r\n#define ArB x/x/9-77-8\r\n#define j 76-6/93+vN\r\n#define cALNN Oc+60499\r\n8*6-66/x*x\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define fSdvwOj (W)*W+73\r\n#define NAZjc 7695*55-x\r\n#define AHGGglVwch (6-a-W)\r\n((5))+W+W\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define m bJJD +x \r\n#define yYkQNzjR (x*19)-892\r\n#define MNvfxqfbq (x-6*x/8)\r\n#define nJZdvO 8/4 *m/m\r\n 9+m/x+x\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define Sl x*7-(x)/O\r\n#define srAOHccTln 3+x*2*O\r\n#define OFAZk 239751817\r\n#define JYWrOEgazV (x-O/4)-x\r\n#define XsOZvalgOh 89905879/7\r\nx/Sl-(Sl)\r\n', 'output': ['Suspicious\r\n']}, {'input': '3\r\n#define uYdw ((9-x-3) )\r\n#define fy (((x+21)))\r\n#define nY ((2+x)-46)\r\n141141432\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define GCvqH (58 )-(x)\r\n#define g ((x/x+x))\r\n#define spst hQTJ\r\n#define i GCvqH\r\n(((x+6)))\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define rg (67)+((x))\r\n#define ya x-(6/x)*rg\r\n#define anTxe 10*ya*(x)\r\n#define xcmo ((x)*(vT))\r\n#define eg ((vT)) -ya\r\n((x*(Ii)))\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define T ((b/1 +1))\r\n#define pm (s)-43-(s)\r\n#define jkNBpvDZl ((x ))/65\r\n(((58*7)))\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define cJitUt 21/(4)+4+4\r\n#define zHwBOLIvF 4*((41/x))\r\n#define GbtYVo (E)+(x+3)\r\n#define zTcZBaby (58)+x-x+x\r\n(E+E)/8 *4\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define mBURKdeKvy 266693986\r\n#define nWi ( ((x))-4)\r\n#define iYreeOt ((7/x+42))\r\n#define laLzP ((aB/35)) \r\n#define dXjRJ (((B*hX)))\r\n(1*2+(67))\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define UVMQLGvEqOxaAgRkvJH tBd\r\n#define QoAsBMaUcJzXai x/x-hm/83+8*8/5/hm /x/hm\r\n#define QtxtzEHCmidm 75 +491928441\r\n((x)/VUpYoEdDUtLFanGyqfQR  )\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define efemx 2/1*3*69+81+10/690445104\r\n#define AyjrEzAjMKZpRPfCOaO 21*9+( j*40+3*4)*ND+w-j*j+x*55\r\n#define YkJkHcNhXcci 85*3215/40/365819568\r\n#define MUzvOZSXJujI 9-4/j*j-7-w*23*5+j+9-9*ND*2/37\r\nND/j*28 -1* ND+22889023/j/j/j\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define QNUkjqPcGWF 6*4/908975666-7/10-x*7\r\n#define xqwhNWiiMaZOcmgiXYY 3936*(e*5*H+2)-TsA+(e)/1-25\r\n#define tRsSqfqJt ((uT*82/e)+e/(23+(45)-9)+(50))\r\n#define DtIOWRkYe (8*3/9)*e*x *60041512*2-(e)\r\n#define qgPgxja (4/x+e/uT*16358009- 6/13*5)\r\ne+x*e/84/x+uT*H\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define lTCUUO JQmj\r\n#define oUeQMB (12*x+x+x)-75-(79/1)-(7)*1/mr\r\n#define LAQu xwvBtky\r\n8654 *1*5-mr-3*J/oUeQMB/x/6/9\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define VLuQIO 1-x/33+ Fk+wS/35-wS-(x*iz )\r\n#define BCIsIR 5*(wS)/x/iz/1+x-x-4-x/68/x/8*x\r\n#define QPUpmTiB 21-x/895912506+2\r\n#define wcZLUIqJS 7/65-x*61-(24+iz)+x+315670+x/x\r\nBCIsIR/VLuQIO\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define FDmMYOENCOKmYwYlOl 6-(L)/((((ud/x))/ud-26*8-5))\r\n#define QkopKBjKdJxhc (6)*4/7-L/781844832  \r\n#define UjgTieUBXTSTbiLFAhkV 3*1*(52)/6-6*65/x+((L-56))+x+x\r\n#define yWVYDuqliezpKLwnI 8/4+1+88+97946+(1)-((68))-L/L\r\n#define AvvED 719901121+95/2/78/1-10+37\r\n(1*x+ 528176190+17/ud)\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define e x *R/5+(x)+4/18/x*R/x-8+1+R\r\n#define GgGqGYjXoJjIezAVu (( 491563947*R))*9-e-3/4\r\n#define XgznGUWMxQwh (8/R+4*(e)+10/4*x+24*R+21)-224\r\n (82493582)\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define MrKSTrKhPLeJqOcEPvv (x+x/x)/Qdf-x-x-(2/23)+9442-x\r\n#define zPHUgmIYE 10- 7*x/x+VwRUuIRezDR*80\r\n#define OsfThxasHeFZCEZTfD 271456028-(x*x)-8+2*x*x*x+(x)\r\n#define zVYasB x/x -x-(51)-x*x*((x))  /x \r\n(x/64-x*( (5+x+x)-(37)/3*22))\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define WREol (fcdGZaLzhiFpVQmhHO)\r\n#define lDTNxcMqPPP 3+(57)/x/91540-x*71-x*6-((1))\r\n#define afFJVBkr ((12*x-8+9 *lDlx+7+lDlx))\r\n#define mYEizEWrNtRSQNCcDQrn 732480960+9+x-78-x/1+12*x\r\n#define IZTmjheAahbNSNFa ((x-x*7+407643063 ))\r\nXQvMxLNpQnhpimNhAkfX\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define Mc x+x*55231- x/x/x+35/x*(5*(x)) -5*x*(1-2-(29/1))\r\n#define afSVLCdjvylSu bgqv/6+4*x*((Mc/1318/x-8-4)-Mc/Mc/(9))\r\n#define ZOSV (1+2/x+6* 174806683)-x/x*Mc+52*x-x\r\nbgqv-x-6*x/72/(x )/afSVLCdjvylSu\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define RJIiiGQqn dmpWFcrqQeM+V-o* 55/9*o-o/V*V*o\r\n#define ElDZlrtzDkeKgsX 498718105* 3/(y)/(4)-(5*x)*1\r\n#define qwKl jHqPHX\r\n#define qXzAZkCuchBYR  (qy*qwKl-6+5*1+2)-7-3+(38)-o*4/4-1-V*x/6+1*x/o\r\no*((V))-o+2+((((2*V)/V-o*V/4)))/o*33+y/7  -x+x \r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define WTovyGexUNjGMRJv (MQG*18-6)/x/x*x/x-x*akNyw*x+x-x/2/x*20\r\n#define hpextyhVCa 70*x/67-x*87931-(497612505-7*x-MQG)-x\r\n#define MRkKnCXFt x-5-21962-x/sOmThNSS/x/6-4+(65+57+x+x+7-7+x/x)\r\n#define ajsczBLLklBSqqh nGj-38*9 *x/47/8*5/5-72/x*x-x*x*31  /7-44-3+64\r\n#define jgqfv WTovyGexUNjGMRJv\r\n  4+338/x*x+13 -795*3-74*2/4+563-x/76401438/83025\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define G u+13-35348/2-(u/u)-u/u*u*(OC)-OC -u-u/u*u/9 \r\n#define RNRQ G*G*u+G/755750/G/G +((u-6*G+6)*2)- 5*96+5/u*275-u\r\n#define Zg 94363/u*u-41+Gm*G-81/5-1-G*G*x-(5517*5/4)*21 +75\r\n406690013/WM*G+(u+u)*Zg+2\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define RMWAZhIp x*x+12+94*12*5*1-x-141915293\r\n#define EeguG 9-55+x/29+x+x/E*8*81/x-x*75-4*17-81/x/6+619978*x*x\r\n#define HvUYEvQTyYmBGvqHSb 454574730/644135926*x/23+E-sy/14\r\n#define BqMGcT x/(43)+819897061-x*(7/x)-(x)+sy-E-x*79-E+(x)/6/63\r\n76+3/x/8*x+E-76+sy-sy+9*6/66/sy-77+x-x*sy+E/50/64\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define cbt ((((d))+9-3+ (d)/d/6*SDDNqj*50/d+d-m+8/d/1)) \r\n#define gLrUE 18+ 70*d/3-d*d-d/35 +33-5/9+d-d*387+d-1\r\n#define AvjmK 9-d-8+(d+m+5/2/x*d+1)/x/d-5-2*(m)+d+17/d+ 4/52/8\r\n#define SjrJ 90/7/5/d+ 254877982+(m) *x-19\r\n#define PlykoqfDbwxR  540304590 +d*x/11-(m+d-d-4)*(d-3-1)/d\r\nd-2+1+46-29620+9-(9*3 /d)*6*m/d+9+(1670)/cbt/d+d\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define BuAiJLgAlkj x-3+419032556/409023036-(17*84)+x+8+A\r\n#define wU 516506880\r\n#define HeyDGlnaGxBaHjzelvF iRSPqHfgHw/4-(99)*(I)+A+I-9*46*x\r\nI/CRklg-HeyDGlnaGxBaHjzelvF/3+5 \r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define SOlTohcPGckDyF ((D)/G-83+KHGSuJFLHqD/5)\r\n#define KEUXeOYpg 9+x-8-8/x/9-65-6+4+55*x-58/x+84+D*2-7+D/x-x*G/4-2\r\n#define YZl (1/67*x*6/2*G)-D/1595107*D+6/x*1+D+3/9/x/26-6+9 \r\n#define gCatFsZn uBBqilYclMhpVfKKTkGK\r\n(28682537+ YZl*(4*52)  )*x/8- gCatFsZn*x/54/7\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define iiXEqDYeyVmIYsOaO fj/x-9-6/x*x+ 1/ 7*2-x -x+9+235*23*Ww+x-2*K+2-x/70\r\n#define XVgLzhoTUxoBr ( x+x/x/x*6-x)* x+K/24206-2 /5/8-x-7/Ww/K-x+6 \r\n#define QdfRBaJk 470551685-(  54-x)-30\r\n#define gEJcAGnF x+x-x+(x/x+9)/x-41-1/fj/1157561+x/x -x/26/x+K*x\r\n#define lO 7-1*(x*58 )-K*fj  /722113691/x/K+2\r\n2+4*85/86/x*27 /49252-x*x/6-83-7/x+x+K-lO+8-K-x\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nr-sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x+y\r\nr*sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x-y\r\nr-sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nr*sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x*y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nr-sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nr*sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x/y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nr-sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nr*sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum*r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum/r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum*r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum/r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum*r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum/r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum*r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum/r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define x 3/2\r\n2*x\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n   #    define     sum     1000000000   +   1000000000       +     1000000000      \r\n    #    define      a    b     +      45    *   sum    \r\n       a       \r\n', 'output': ['Suspicious\r\n']}]


Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges.

The first line of input contains two integers n and m (1 ≤ n ≤ 19, 0 ≤ m) – respectively the number of vertices and edges of the graph. Each of the subsequent m lines contains two integers a and b, (1 ≤ a, b ≤ n, a ≠ b) indicating that vertices a and b are connected by an undirected edge. There is no more than one edge connecting any pair of vertices.

Output the number of cycles in the given graph.

NoteThe example graph is a clique and contains four cycles of length 3 and three cycles of length 4.

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

typedef long long ll;

ll dp[19][262144]; /* at, mask */
int g[32][32];
int v,e;
int bc[262144];

void printmask(int mask) {
  int i;
  for(i=0;i<v;i++) printf("%c",(mask&(1<<i))?'1':'0');
}

/* count cycles going through first, with no nodes >first */
ll solve(int first,int at,int mask) {
  ll res=0;
  int i;
  if(dp[at][mask]>-1) return dp[at][mask];
  /* can go back? only if cycle is of length >=3 */
  if(g[first][at] && bc[mask]>=2) res++;
  for(i=0;i<first;i++) if(g[at][i] && !(mask&(1<<i))) {
    res+=solve(first,i,mask|(1<<i));
  }
/*  printf("cycle at %d %d, mask ",first,at);
  printmask(mask);
  printf(": %I64d\n",res);*/
  return dp[at][mask]=res;
}

int main() {
  int i,j,a,b;
  ll ans=0,res;
  bc[0]=0;
  for(i=1;i<262144;i++) bc[i]=bc[i>>1]+(i&1);
  scanf("%d %d",&v,&e);
  memset(g,0,sizeof(g));
  for(i=0;i<e;i++) {
    scanf("%d %d",&a,&b);
    g[a-1][b-1]=g[b-1][a-1]=1;
  }
  for(i=2;i<v;i++) {
    for(j=0;j<=i;j++) memset(dp[j],-1,sizeof(ll)*(1<<i));
    res=solve(i,i,0);
    ans+=res;
/*    printf("end at %d %I64d\n",i,res);*/
  }
  ans/=2;
#ifdef _WIN32
  printf("%I64d\n",ans);
#else
  printf("%lld\n",ans);
#endif
  return 0;
}


Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.

The only input line contains three space-separated integers b, n and c (2 ≤ b < 10106, 1 ≤ n < 10106, 1 ≤ c ≤ 109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.

In the only line output the amount of numbers written on the same page as the last number.

NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.

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

#define N	1000000

int main() {
	static char bb[N + 1], nn[N + 1];
	int i, j, lb, ln;
	int a, b, c;

	scanf("%s%s%d", bb, nn, &c);
	lb = strlen(bb), ln = strlen(nn);
	b = 0;
	for (i = 0; i < lb; i++)
		b = ((long long) b * 10 + (bb[i] - '0')) % c;
	a = (b - 1 + c) % c;
	for (i = ln - 1; i >= 0; i--) {
		if (nn[i] != '0') {
			nn[i]--;
			break;
		}
		nn[i] = '9';
	}

	for (i = ln - 1; i >= 0; i--) {
		int p = 1;

		for (j = 0; j < nn[i] - '0'; j++) /*expanded notation*/
			a = (long long) a * b % c;
		for (j = 0; j < 10; j++)
			p = (long long) p * b % c;
		b = p;
	}
	printf("%d\n", a == 0 ? c : a);
	return 0;
}


One day n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i - j| = di, where di is a favourite number of i-th cell. Cells make moves in any order, the number of moves is unlimited.The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to n. You are to determine whether the game could move to this state.

The first line contains positive integer n (1 ≤ n ≤ 100) — the number of cells in the array. The second line contains n distinct integers from 1 to n — permutation. The last line contains n integers from 1 to n — favourite numbers of the cells.

If the given state is reachable in the described game, output YES, otherwise NO.

#include <stdio.h>

int par[100];

int find(int x)
{
     if (par[x] == x) {
	  return x;
     } else {
	  return par[x] = find(par[x]);
     }
}

void unite(int x, int y)
{
     x = find(x);
     y = find(y);

     if (x == y) return;

     par[x] = y;
}

int same(int x, int y)
{
     x = find(x);
     y = find(y);

     if (x == y) {
	  return 1;
     } else {
	  return 0;
     }
}

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

     scanf("%d", &n);

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

     for (i = 0; i < n; i++) par[i] = i;

     for (i = 0; i < n; i++) {
	  if (b[i] <= i) {
	       unite(i, i - b[i]);
	  }

	  if (b[i] + i < n) {
	       unite(i, b[i] + i);
	  }
     }

     for (i = 0; i < n; i++) {
	  if (same(i, a[i] - 1) == 0) {
	       puts("NO");

	       return 0;
	  }
     }

     puts("YES");

     return 0;
}


The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.

The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999).

Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes).

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

int d[2000],n;

void change(int ix,int min) {
  char s[10],b;
  int i,j,v,best=9999;
  if(d[ix]>9999) d[ix]=9999;
  sprintf(s,"%d",d[ix]);
  for(i=0;i<4;i++) {
    b=s[i];
    for(j=0;j<10;j++) {
      if(i==0 && j==0) continue;
      s[i]=j+48;
      v=strtol(s,0,10);
      if(best>v && v>=min) best=v;
    }
    s[i]=b;
  }
  d[ix]=best;
}

int main() {
  int i;
  scanf("%d",&n);
  for(i=0;i<n;i++) scanf("%d",&d[i]);
  change(0,1000);
  for(i=1;i<n;i++) change(i,d[i-1]);
  if(d[n-1]<2012) {
    for(i=0;i<n;i++) printf("%d\n",d[i]);
  } else puts("No solution");
  return 0;
}


You are given a sequence of balls A by your teacher, each labeled with a lowercase Latin letter 'a'-'z'. You don't like the given sequence. You want to change it into a new sequence, B that suits you better. So, you allow yourself four operations:  You can insert any ball with any label into the sequence at any position.  You can delete (remove) any ball from any position.  You can replace any ball with any other ball.  You can exchange (swap) two adjacent balls. Your teacher now places time constraints on each operation, meaning that an operation can only be performed in certain time. So, the first operation takes time ti, the second one takes td, the third one takes tr and the fourth one takes te. Also, it is given that 2·te ≥ ti + td.Find the minimal time to convert the sequence A to the sequence B.

The first line contains four space-separated integers ti, td, tr, te (0 < ti, td, tr, te ≤ 100). The following two lines contain sequences A and B on separate lines. The length of each line is between 1 and 4000 characters inclusive.

Print a single integer representing minimum time to convert A into B.

NoteIn the second sample, you could delete the ball labeled 'a' from the first position and then insert another 'a' at the new second position with total time 6. However exchanging the balls give total time 3.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define REP(i,a,b) for(i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)

int dp[4100][4100];
char a[4100], b[4100]; int as, bs;
int cost[4];
int nextA[4100][26], nextB[4100][26];

int solve(int A,int B){
  int i,j,k;
  int res = 1000000000, tmp;

  if(dp[A][B] >= 0) return dp[A][B];
  if(A==0 && B==0) return dp[A][B] = 0;
  if(A==0 || B==0) return dp[A][B] = cost[1] * A + cost[0] * B;
  if(a[A-1] == b[B-1]) return dp[A][B] = solve(A-1,B-1);

  tmp = cost[1] + solve(A-1,B);
  if(res > tmp) res = tmp;

  tmp = cost[0] + solve(A,B-1);
  if(res > tmp) res = tmp;

  tmp = cost[2] + solve(A-1,B-1);
  if(res > tmp) res = tmp;

  if(A>=2 && B>=2){
    j = nextA[A-1][b[B-1]-'a'];
    k = nextB[B-1][a[A-1]-'a'];
    if(j>=0 && k>=0){
      tmp = (A-j-2)*cost[1] + (B-k-2)*cost[0] + cost[3];
      tmp += solve(j,k);
      if(res > tmp) res = tmp;
    }
  }

  return dp[A][B] = res;
}

int main(){
  int i,j,k,l,m,n;

  while(scanf("%d%d%d%d%s%s",cost,cost+1,cost+2,cost+3,a,b)==6){
    for(i=0;;i++) if(a[i]<' ') break; as = i;
    for(i=0;;i++) if(b[i]<' ') break; bs = i;

    rep(i,26) nextA[0][i] = -1;
    rep(k,as){
      nextA[k][a[k]-'a'] = k;
      rep(i,26) nextA[k+1][i] = nextA[k][i];
    }

    rep(i,26) nextB[0][i] = -1;
    rep(k,bs){
      nextB[k][b[k]-'a'] = k;
      rep(i,26) nextB[k+1][i] = nextB[k][i];
    }

    rep(i,as+1) rep(j,bs+1) dp[i][j] = -1;
    k = solve(as,bs);
    printf("%d\n",k);
  }

  return 0;
}

[{'input': '1 1 1 1\r\nyoushouldnot\r\nthoushaltnot\r\n', 'output': ['5\r\n']}, {'input': '2 4 10 3\r\nab\r\nba\r\n', 'output': ['3\r\n']}, {'input': '1 10 20 30\r\na\r\nza\r\n', 'output': ['1\r\n']}, {'input': '2 6 10 4\r\nmanthan\r\nmathmania\r\n', 'output': ['12\r\n']}, {'input': '5 1 5 3\r\nabhishek\r\naurbhishek\r\n', 'output': ['10\r\n']}, {'input': '1 1 100 1\r\nabcd\r\nwxyz\r\n', 'output': ['8\r\n']}, {'input': '4 6 5 5\r\ntest\r\ntsar\r\n', 'output': ['15\r\n']}, {'input': '2 4 10 3\r\nmanthan\r\nnahtnam\r\n', 'output': ['15\r\n']}, {'input': '2 4 100 3\r\nabcd\r\nbade\r\n', 'output': ['9\r\n']}, {'input': '5 5 1 5\r\nab\r\nba\r\n', 'output': ['2\r\n']}, {'input': '3 5 100 4\r\ntets\r\ntesat\r\n', 'output': ['7\r\n']}, {'input': '9 1 10 5\r\nabcd\r\ndbca\r\n', 'output': ['20\r\n']}, {'input': '2 2 10 2\r\nabcd\r\nadcb\r\n', 'output': ['6\r\n']}, {'input': '8 4 3 10\r\neekoowppum\r\njgmtlmeuigztfctikegvakfbgbafytbputmeppkuuyjkhagdsftfoueitnhjllolevgpmbtlworxojyzpfdaasckcqqdwdwwrklb\r\n', 'output': ['729\r\n']}, {'input': '5 5 1 82\r\nzmtuomrwesrhvudogmalwhtktfcbglnpbdntqssjcrdwlerfccmkmmhsfgaocchxdxxmeiaunhellstnhnjjmbynmqlzuupbnkrw\r\nglpfybikah\r\n', 'output': ['453\r\n']}, {'input': '20 21 22 84\r\notirbgzzphwwxqtgqyxympiumuyoupngwabrprmyhjpkgpjmez\r\nozvimdjwsyuacgbekgcw\r\n', 'output': ['872\r\n']}, {'input': '4 5 6 62\r\nqibkeavwalpn\r\nmaasevryyxzzqpdcgydb\r\n', 'output': ['89\r\n']}, {'input': '9 8 7 67\r\nejohycekbciwahqybwiy\r\ncpxgvbiwnuytmbwjvrzalydjjgdcmczejwesqrrh\r\n', 'output': ['299\r\n']}, {'input': '44 55 22 80\r\nabcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz\r\n', 'output': ['0\r\n']}, {'input': '63 9 44 72\r\nabdabdabdabdabdabdabdabdabdabdabdabdabdabdabdabdabdabdabdabdabdabdabdabd\r\nabdabdabdabdabdabdabdabdabdabdabtdabdabdabdabdabdabdabdabdabdabdabdabdabd\r\n', 'output': ['63\r\n']}, {'input': '1 3 4 2\r\nabc\r\ncxa\r\n', 'output': ['6\r\n']}, {'input': '1 1 1 1\r\nacccb\r\nba\r\n', 'output': ['4\r\n']}, {'input': '1 1 1 1\r\nab\r\nbca\r\n', 'output': ['2\r\n']}, {'input': '1 1 1 1\r\nba\r\nacb\r\n', 'output': ['2\r\n']}, {'input': '1 1 100 1\r\nafffb\r\nbggga\r\n', 'output': ['7\r\n']}, {'input': '1 1 1 1\r\nab\r\nbccccccccccccccccccca\r\n', 'output': ['20\r\n']}, {'input': '100 1 100 60\r\nacb\r\nba\r\n', 'output': ['61\r\n']}]


Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:1) The boss has two parameters: max — the initial amount of health and reg — regeneration rate per second.2) Every scroll also has two parameters: powi — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).The boss is considered to be defeated if at the end of a second he has nonpositive ( ≤ 0) amount of health.Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.

The first line contains three integers N, max and reg (1 ≤ N, max, reg ≤ 1000) –– the amount of scrolls and the parameters of the boss. The next N lines contain two integers powi and dmgi each — the parameters of the i-th scroll (0 ≤ powi ≤ 100, 1 ≤ dmgi ≤ 2000).

In case Petya can’t complete this level, output in the single line NO. Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds. Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated.

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

#define maxN 1200

int main(){
	int i,j,k,l,m,n,tm;
	int used[maxN], dmg[maxN], pw[maxN], hp;
	int res[maxN], use_tm[maxN], res_size;
	int maxHP, reg, mx;

	scanf("%d%d%d",&n,&maxHP,&reg);
	for(i=0;i<n;i++) scanf("%d%d",pw+i,dmg+i);

	hp = maxHP;
	for(i=0;i<n;i++) used[i]=0;
	res_size=0;

	for(tm=0;;tm++){
		int fg=0, bef_hp = hp;

		for(i=0;i<n;i++) if(used[i]) hp -= dmg[i];
		hp += reg;
		if(hp > maxHP) hp = maxHP;

		if(hp<=0) break;

		mx = 0;
		for(i=0;i<n;i++) if(!used[i]) if(pw[i]*maxHP >= hp*100) if(mx < dmg[i]){
			mx = dmg[i]; k = i;
		}
		if(mx){
			fg++;
			used[k] = 1;
			res[res_size]=k+1; use_tm[res_size] = tm;
			res_size++;
		}

		if(bef_hp > hp) fg++;

		if(!fg) break;
	}

	if(hp > 0)puts("NO");
	else{
		puts("YES");
		printf("%d %d\n",tm,res_size);
		for(i=0;i<res_size;i++) printf("%d %d\n",use_tm[i],res[i]);
	}

	return 0;
}


Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books. You are not informed on what crime was committed, when and where the corpse was found and other details. We only know that the crime was committed in a house that has n rooms and m doors between the pairs of rooms. The house residents are very suspicious, that's why all the doors can be locked with keys and all the keys are different. According to the provided evidence on Thursday night all the doors in the house were locked, and it is known in what rooms were the residents, and what kind of keys had any one of them. The same is known for the Friday night, when all the doors were also locked. On Friday it was raining heavily, that's why nobody left the house and nobody entered it. During the day the house residents could  open and close doors to the neighboring rooms using the keys at their disposal (every door can be opened and closed from each side);  move freely from a room to a room if a corresponding door is open;  give keys to one another, being in one room.  "Little grey matter" of Hercule Poirot are not capable of coping with such amount of information. Find out if the positions of people and keys on the Thursday night could result in the positions on Friday night, otherwise somebody among the witnesses is surely lying.

The first line contains three preset integers n, m и k (1 ≤ n, m, k ≤ 1000) — the number of rooms, the number of doors and the number of house residents respectively. The next m lines contain pairs of room numbers which join the doors. The rooms are numbered with integers from 1 to n. There cannot be more that one door between the pair of rooms. No door connects a room with itself. The next k lines describe the residents' position on the first night. Every line contains a resident's name (a non-empty line consisting of no more than 10 Latin letters), then after a space follows the room number, then, after a space — the number of keys the resident has. Then follow written space-separated numbers of the doors that can be unlocked by these keys. The doors are numbered with integers from 1 to m in the order in which they are described in the input data. All the residents have different names, uppercase and lowercase letters considered to be different. Every m keys occurs exactly once in the description. Multiple people may be present in one room, some rooms may be empty. The next k lines describe the position of the residents on the second night in the very same format. It is guaranteed that in the second night's description the residents' names remain the same and every m keys occurs exactly once.

Print "YES" (without quotes) if the second arrangement can result from the first one, otherwise, print "NO".

2 1 2
1 2
Dmitry 1 1 1
Natalia 2 0
Natalia 1 1 1
Dmitry 2 0

4 4 3
1 3
1 2
2 3
3 4
Artem 1 1 4
Dmitry 1 1 2
Edvard 4 2 1 3
Artem 2 0
Dmitry 1 0
Edvard 4 4 1 2 3 4


Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.

The first input line contains two integers n and m (6 ≤ n ≤ 35, 1 ≤ m ≤ 10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow m lines, each containing space-separated si and ci which correspondingly indicate Vasya’s attempt (a line containing n numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).

Print the single number which indicates how many possible code variants that do not contradict the m system responses are left.

#include <stdio.h>

int n,m;
char input[11][36] = {{'\0'},{'\0'}};
int errors[11] = {0};
int poss = 0;
char arr[36] = {0};
int visited[11] = {0};
int check()
{
    int counter =0;
    for (int i=0;i<m;i++)
    {
        int counter=0;
        for (int j =0;j<n;j++)
        {
            if (input[i][j] != arr[j])
                counter++;
        }
        if (counter != errors[i])
            return 0;
    }
    return 1;
}
char change(char num)
{
    if (num == '0')
        return '1';
    else
        return '0';
}

void solve (int place,int var)
{
    if (var == 0)
    {
        if (check())
            poss++;
            return;
    }
    if (place == n)
        return;
    arr[place] =change(arr[place]);
    solve(place+1,var-1);
    arr[place] = change(arr[place]);
    solve (place+1,var);
}

int main()
{
    int max=0,max_index = 0;
    scanf("%i %i",&n,&m);
    for (int i =0;i<m;i++)
    {
        scanf("%s %i",&input[i],&errors[i]);
        if (errors[i] > max)
        {
            max = errors[i];
            max_index = i;
        }
    }
//    for (int i =0;i<m;i++)
//    {
//        strcpy(arr,input[i]);
//        solve(0,errors[i]);
//    }
//    printf("%i",poss/m);
    strcpy(arr,input[max_index]);
    solve(0,errors[max_index]);
    printf("%i",poss);
}


In the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away from the uncorrupted part, the crimes could be stopped. So, they are trying to set up a compound where they can keep the corrupted people. To ensure that the criminals don't escape the compound, a watchtower needs to be set up, so that they can be watched.Since the people of Aalam-Aara aren't very rich, they met up with a merchant from some rich town who agreed to sell them a land-plot which has already a straight line fence AB along which a few points are set up where they can put up a watchtower. Your task is to help them find out the number of points on that fence where the tower can be put up, so that all the criminals can be watched from there. Only one watchtower can be set up. A criminal is watchable from the watchtower if the line of visibility from the watchtower to him doesn't cross the plot-edges at any point between him and the tower i.e. as shown in figure 1 below, points X, Y, C and A are visible from point B but the points E and D are not.    Figure 1     Figure 2 Assume that the land plot is in the shape of a polygon and coordinate axes have been setup such that the fence AB is parallel to x-axis and the points where the watchtower can be set up are the integer points on the line. For example, in given figure 2, watchtower can be setup on any of five integer points on AB i.e. (4, 8), (5, 8), (6, 8), (7, 8) or (8, 8). You can assume that no three consecutive points are collinear and all the corner points other than A and B, lie towards same side of fence AB. The given polygon doesn't contain self-intersections.

The first line of the test case will consist of the number of vertices n (3 ≤ n ≤ 1000). Next n lines will contain the coordinates of the vertices in the clockwise order of the polygon. On the i-th line are integers xi and yi (0 ≤ xi, yi ≤ 106) separated by a space. The endpoints of the fence AB are the first two points, (x1, y1) and (x2, y2).

Output consists of a single line containing the number of points where the watchtower can be set up.

NoteFigure 2 shows the first test case. All the points in the figure are watchable from any point on fence AB. Since, AB has 5 integer coordinates, so answer is 5.For case two, fence CD and DE are not completely visible, thus answer is 0.

/* practice with Dukkha */
#include <stdio.h>

#define N	1000

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

int xx[N], yy[N];

long long cross2(long long x1, long long y1, long long x2, long long y2) {
	return x1 * y2 - x2 * y1;
}

long long cross(int i, int j, int k) {
	return cross2(xx[j] - xx[i], yy[j] - yy[i], xx[k] - xx[i], yy[k] - yy[i]);
}

int main() {
	int n, i, flip, x, y, l, r;

	scanf("%d", &n);
	for (i = 0; i < n; i++)
		scanf("%d%d", &xx[i], &yy[i]);
	flip = xx[0] < xx[1];
	x = xx[1], y = yy[1];
	for (i = 0; i < n; i++) {
		xx[i] -= x;
		yy[i] -= y;
		if (flip) {
			xx[i] = -xx[i];
			yy[i] = -yy[i];
		}
	}
	l = 0, r = xx[0];
	for (i = 2; i + 1 < n; i++) {
		long long cr = cross(i, i + 1, 0);
		long long cl = cross(i, i + 1, 1);
		int x0, y0, x1, y1;

		if (cr > 0 && cl > 0) {
			printf("0\n");
			return 0;
		}
		x0 = xx[i], y0 = yy[i], x1 = xx[i + 1], y1 = yy[i + 1];
		if (cr > 0 || cl > 0) {
			long long p = (long long) x0 * (y1 - y0) - (long long) y0 * (x1 - x0);
			long long q = y1 - y0;

			if (q < 0)
				p = -p, q = -q;
			if (cr > 0)
				r = min(r, p / q);
			else
				l = max(l, (p + q - 1) / q);
		}
	}
	printf("%d\n", l <= r ? r - l + 1 : 0);
	return 0;
}