n,l = [int(nl) for nl in raw_input().split(" ")]
a = [int(ai) for ai in raw_input().split(" ")]
ans = 0
sma = sum(a)
for lx in range(l,sma+1):
	ansx = sma/lx
	if (ansx*lx) > ans:
		ans = ansx * lx
print ans

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

The first output line contains two space-separated integers n and l (1 ≤ n, l ≤ 100). They are the number of stripes in the warehouse and the minimal acceptable length of a blind stripe in bourlemeters. The second line contains space-separated n integers ai. They are the lengths of initial stripes in bourlemeters (1 ≤ ai ≤ 100).

Print the single number — the maximal area of the window in square bourlemeters that can be completely covered. If no window with a positive area that can be covered completely without breaking any of the given rules exist, then print the single number 0.

NoteIn the first sample test the required window is 2 × 4 in size and the blinds for it consist of 4 parts, each 2 bourlemeters long. One of the parts is the initial stripe with the length of 2, the other one is a part of a cut stripe with the length of 3 and the two remaining stripes are parts of a stripe with the length of 4 cut in halves.

#!/usr/bin/env python

def main():
	n,l = map(int, raw_input().split())
	d = map(int, raw_input().split())

	ans = 0
	for cut in range(l, max(d)+1):
		w = map(lambda x:x/cut, d)
		ans = max(ans,sum(w)*cut)

	print ans

main()


n,m = list(map(int, input().split()))

arr = []
for _ in range(n):
    arr.append(list(input()))

from collections import defaultdict

visited = defaultdict(lambda: [0] * m)
included = defaultdict(lambda: [True] * m)

def find_for_row_and_cols(row_index, value):
    vals = []
    for i in range(m):
        if arr[row_index][i] == value:
            vals.append((row_index, i))

    for i in range(n):
        if arr[i][col_index] == value:
            vals.append((i, col_index))
    return vals

# def find_for_cols(col_index,)

def find_and_mark(row_index, col_index, value):
    if visited[row_index][col_index]: return

    vals = find_for_row_and_cols(row_index, value)
    visited[row_index][col_index] = 1
    if len(vals) > 2:
        for i, j in vals:
            included[i][j] = False

            if i == row_index and j == col_index:
                continue
            find_and_mark(row_index, col_index, value)

for row_index, row in enumerate(arr):
    for col_index, value in enumerate(row):
        if not visited[row_index][col_index]:
            find_and_mark(row_index, col_index, value)

ans = []
for row_index, row in enumerate(arr):
    for col_index, value in enumerate(row):
        if included[row_index][col_index]:
            ans.append(arr[row_index][col_index])

print(''.join(ans))

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

The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.

Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.

n, m = list(map(int, input().strip().split()))
A = [[0] * m] * n

for r in range(n):
    A[r] = list(input().strip())

def in_row(A, r, c):
    x = A[r][c]
    left, right = A[r][:c], A[r][c + 1:]
    if (x in left) or (x in right):
        return True

def in_col(A, r, c):
    x = A[r][c]
    for row in range(n):
        if row == r:
            continue
        if A[row][c] == x:
            return True

out = ''
for r in range(n):
    for c in range(m):
        if not in_row(A, r, c) and not in_col(A, r, c):
            out += A[r][c]

print(out)

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


#include <bits/stdc++.h>
#define ll long long
#define M 1000000007
#define INF 9223372036854775807
#define mp(x,y) make_pair(x,y)
#define pb(x) push_back(x)
#define pmp(x,y) pb(mp(x,y))
#define ld double
#define PI 3.14159265
#define len(a) (ll)a.size()
#define F first
#define S second
#define ch cout<<"debug\n"
#define fast() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;

ll a[2001][2001],n,b[2001][2001];

void pre()
{
	ll sum=0;

	for(ll k=0;k<n;k++)
	{

		sum=0;

		for(ll i=0;i<n-k;i++)
			sum+=a[i][i+k];

		for(ll i=0;i<n-k;i++)
			b[i][i+k]=sum;

		sum=0;

		for(ll i=0;i<n-k;i++)
			sum+=a[i+k][i];

		for(ll i=0;i<n-k;i++)
			b[i+k][i]=sum;
	}

	for(ll k=0;k<n;k++)
	{
		sum=0;

		for(ll i=0;i<n-k;i++)
			sum+=a[i+k][n-1-i];

		for(ll i=0;i<n-k;i++)
			b[i+k][n-1-i]+=sum;

		sum=0;

		for(ll i=0;i<n-k;i++)
			sum+=a[i][n-1-i-k];

		if(k!=0)
		for(ll i=0;i<n-k;i++)
			b[i][n-1-i-k]+=sum;

	}

	for(ll i=0;i<n;i++)
		for(ll j=0;j<n;j++)
			b[i][j]-=a[i][j];
}

void pre2(){

	ll ans1=0,ans2=0;
	for(ll i=0;i<n;i++)
	{
		for(ll j=0;j<n;j++)
		{
			if((i+j)%2)
				ans1=max(ans1,b[i][j]);

			else
				ans2=max(ans2,b[i][j]);
		}
	}

	cout<<ans1+ans2<<endl;

	for(ll i=0;i<n;i++)
	{
		for(ll j=0;j<n;j++)
		{
			if((i+j)%2 and ans1==b[i][j])
			{
				cout<<i+1<<" "<<j+1<<" ";
				ans1=-1;
			}

			else if(ans2==b[i][j] and (i+j)%2==0)
			{
				cout<<i+1<<" "<<j+1<<" ";
				ans2=-1;
			}
		}
	}

}

void print()
{
	cout<<endl;
	for(ll i=0;i<n;i++){
		for(ll j=0;j<n;j++)
			cout<<b[i][j]<<" ";
		cout<<endl;
	}
}

int main(){

	fast();
	cin>>n;
	for(ll i=0;i<n;i++)
		for(ll j=0;j<n;j++)
			cin>>a[i][j];

	pre();
//	print();
	pre2();
	return 0;
}

One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7).

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.

Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7).

NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB".

n, m = map(int, raw_input().split())

nomes = []

for i in xrange(n):
	entrada = raw_input()
	nomes.append(entrada)

total = 1

for k in xrange(m):

	parcial = [nomes[0][k]]
	for l in xrange(1, n):

		if(nomes[l][k] not in parcial):
			parcial.append(nomes[l][k])

	total *= len(parcial)

print total % 1000000007

[{'input': '2 3\r\nAAB\r\nBAA\r\n', 'output': ['4\r\n']}, {'input': '4 5\r\nABABA\r\nBCGDG\r\nAAAAA\r\nYABSA\r\n', 'output': ['216\r\n']}, {'input': '1 1\r\nE\r\n', 'output': ['1\r\n']}, {'input': '2 2\r\nNS\r\nPD\r\n', 'output': ['4\r\n']}, {'input': '3 4\r\nPJKD\r\nNFJX\r\nFGFK\r\n', 'output': ['81\r\n']}, {'input': '4 5\r\nSXFMY\r\nATHLM\r\nKDDQW\r\nZWGDS\r\n', 'output': ['1024\r\n']}, {'input': '20 14\r\nJNFKBBBJYZHWQE\r\nLBOKZCPFNKDBJY\r\nXKNWGHQHIOXUPF\r\nDDNRUKVUGHWMXW\r\nMTIZFNAAFEAPHX\r\nIXBQOOHEULZYHU\r\nMRCSREUEOOMUUN\r\nHJTSQWKUFYZDQU\r\nGMCMUZCOPRVEIQ\r\nXBKKGGJECOBLTH\r\nXXHTLXCNJZJUAF\r\nVLJRKXXXWMTPKZ\r\nPTYMNPTBBCWKAD\r\nQYJGOBUBHMEDYE\r\nGTKUUVVNKAHTUI\r\nZNKXYZPCYLBZFP\r\nQCBLJTRMBDWNNE\r\nTDOKJOBKEOVNLZ\r\nFKZUITYAFJOQIM\r\nUWQNSGLXEEIRWF\r\n', 'output': ['515139391\r\n']}, {'input': '5 14\r\nAQRXUQQNSKZPGC\r\nDTTKSPFGGVCLPT\r\nVLZQWWESCHDTAZ\r\nCOKOWDWDRUOMHP\r\nXDTRBIZTTCIDGS\r\n', 'output': ['124999979\r\n']}, {'input': '9 23\r\nOILBYKHRGMPENVFNHLSIUOW\r\nLPJFHTUQUINAALRDGLSQUXR\r\nLYYJJEBNZATAFQWTDZSPUNZ\r\nHSJPIQKKWWERJZIEMLCZUKI\r\nOJYIEYDGPFWRHCMISJCCUEM\r\nLMGKZVFYIVDRTIHBWPCNUTG\r\nUBGGNCITVHAIPKXCLTSAULQ\r\nOWSAWUOXQDBSXXBHTLSXUVD\r\nUGQTIZQPBGMASRQPVPSFUWK\r\n', 'output': ['454717784\r\n']}, {'input': '25 4\r\nLVKG\r\nMICU\r\nZHKW\r\nLFGG\r\nOWQO\r\nLCQG\r\nLVXU\r\nOUKB\r\nLNQX\r\nZJTO\r\nOOQX\r\nLVQP\r\nMFQB\r\nMRQV\r\nOIQH\r\nOPXX\r\nXFKU\r\nFCQB\r\nZPKH\r\nLVCH\r\nNFCU\r\nOVQW\r\nOZKU\r\nLFHX\r\nLPXO\r\n', 'output': ['5733\r\n']}, {'input': '30 10\r\nUTNTGOKZYJ\r\nQHOUHNYZVW\r\nLTVGHJRZVW\r\nMZHYHOLZYJ\r\nERYEUEPZYE\r\nUZDBFTURYJ\r\nRVSMQTIZGW\r\nWDJQHMIRYY\r\nKCORHQPZYE\r\nRRPLFOZZVY\r\nJTXMFNNNYJ\r\nMVTGGOZZVV\r\nEHAFFNUZVF\r\nLBRNWJZNYE\r\nJVMOHTPZYJ\r\nWTARFJLZVV\r\nLVJCWOURVW\r\nLCLQFJYRVV\r\nQVBVGNJRYF\r\nNTZGHOLRYE\r\nMGQKHOUPYJ\r\nRRSSBXPZYJ\r\nRYCRGTLZYJ\r\nJRDEGNKRVW\r\nRZKFGHYRVG\r\nMDJBFNIZYG\r\nMPLWHXIZYE\r\nSRZMHMURVE\r\nMTEBBMRZYJ\r\nJPJIFOLZYM\r\n', 'output': ['919913906\r\n']}, {'input': '40 7\r\nPNTVVER\r\nPAHTQDR\r\nRXMJVAS\r\nVIQNLYC\r\nILPUSVX\r\nYJOXQDJ\r\nSEFODTO\r\nOTJMREL\r\nLIQRZGD\r\nLBJJPOR\r\nRUTYHQO\r\nRIWEPBD\r\nKQUMFIB\r\nISTRRYH\r\nXBTOTGK\r\nRFQODEY\r\nHDSTZTP\r\nYCXFAGL\r\nAREGRFU\r\nLELZUYU\r\nGVABDKH\r\nFJAMMME\r\nACVULXE\r\nJHVPJAS\r\nAAQNMBX\r\nJJGUCXG\r\nOQATILQ\r\nNEOSHJM\r\nHFLWOFM\r\nICYEQHY\r\nFACGLYP\r\nPLLXJEQ\r\nDCHXYPB\r\nAGDDZJJ\r\nLSQRXTN\r\nHDQZXIY\r\nNAHDDWW\r\nQCMXRQN\r\nFDUDSZO\r\nHKBEVTW\r\n', 'output': ['206575993\r\n']}, {'input': '2 2\r\nAA\r\nBB\r\n', 'output': ['4\r\n']}, {'input': '1 10\r\nAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '2 8\r\nAAAAAAAA\r\nBBBBBBBB\r\n', 'output': ['256\r\n']}, {'input': '10 10\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDDDDDDD\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDDDDDDD\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\n', 'output': ['1048576\r\n']}, {'input': '1 20\r\nAAAAAAAAAAAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '20 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\n', 'output': ['7\r\n']}, {'input': '5 60\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\nBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\r\nCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC\r\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\r\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\r\n', 'output': ['449874206\r\n']}, {'input': '50 4\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\n', 'output': ['10000\r\n']}, {'input': '1 100\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '100 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\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\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\n', 'output': ['1\r\n']}, {'input': '100 1\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\n', 'output': ['2\r\n']}, {'input': '100 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\n', 'output': ['14\r\n']}, {'input': '100 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\n', 'output': ['26\r\n']}]


n,m=map(int,raw_input().split())
s=[raw_input() for i in range(n)]
p=set(tuple(raw_input().split()) for i in range(m))
from itertools import *
for i in range(n,0,-1):
    for c in combinations(s,i):
        g=0
        for x in c:
            for y in c:
                if x !=y and (x,y) in p:
                    g=1
        if not g:
            print len(c)
            print '\n'.join(c)
            exit()

When little Petya grew up and entered the university, he started to take part in АСМ contests. Later he realized that he doesn't like how the АСМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members efficiently), so he decided to organize his own contests PFAST Inc. — Petr and Friends Are Solving Tasks Corporation. PFAST Inc. rules allow a team to have unlimited number of members.To make this format of contests popular he organised his own tournament. To create the team he will prepare for the contest organised by the PFAST Inc. rules, he chose several volunteers (up to 16 people) and decided to compile a team from them. Petya understands perfectly that if a team has two people that don't get on well, then the team will perform poorly. Put together a team with as many players as possible given that all players should get on well with each other.

The first line contains two integer numbers n (1 ≤ n ≤ 16) — the number of volunteers, and m () — the number of pairs that do not get on. Next n lines contain the volunteers' names (each name is a non-empty string consisting of no more than 10 uppercase and/or lowercase Latin letters). Next m lines contain two names — the names of the volunteers who do not get on. The names in pair are separated with a single space. Each pair of volunteers who do not get on occurs exactly once. The strings are case-sensitive. All n names are distinct.

The first output line should contain the single number k — the number of people in the sought team. Next k lines should contain the names of the sought team's participants in the lexicographical order. If there are several variants to solve the problem, print any of them. Petya might not be a member of the sought team.

n, m = map(int, raw_input().split())
d = [raw_input() for i in xrange(n)]
d.sort()
a = [[0] * n for i in xrange(n)]
for i in xrange(m):
    x, y = raw_input().split()
    a[d.index(x)][d.index(y)] = a[d.index(y)][d.index(x)] = 1
res, bit = 0, 0
for mask in xrange(1 << n):
    num = 0
    for i in xrange(n):
        if mask >> i & 1:
            num += 1
            for j in xrange(i + 1, n):
                if (mask >> j & 1) != 0 and a[i][j]: num = -20
    if res < num: res = num; bit = mask;
print res
for i in xrange(n):
    if bit >> i & 1 : print d[i]

[{'input': '3 1\r\nPetya\r\nVasya\r\nMasha\r\nPetya Vasya\r\n', 'output': ['2\r\nMasha\r\nPetya\r\n']}, {'input': '3 0\r\nPasha\r\nLesha\r\nVanya\r\n', 'output': ['3\r\nLesha\r\nPasha\r\nVanya\r\n']}, {'input': '7 12\r\nPasha\r\nLesha\r\nVanya\r\nTaras\r\nNikita\r\nSergey\r\nAndrey\r\nPasha Taras\r\nPasha Nikita\r\nPasha Andrey\r\nPasha Sergey\r\nLesha Taras\r\nLesha Nikita\r\nLesha Andrey\r\nLesha Sergey\r\nVanya Taras\r\nVanya Nikita\r\nVanya Andrey\r\nVanya Sergey\r\n', 'output': ['4\r\nAndrey\r\nNikita\r\nSergey\r\nTaras\r\n']}, {'input': '2 0\r\nAndrey\r\nTaras\r\n', 'output': ['2\r\nAndrey\r\nTaras\r\n']}, {'input': '16 0\r\nTaras\r\nNikita\r\nSergey\r\nAndrey\r\nRomka\r\nAlexey\r\nUra\r\nDenis\r\nEgor\r\nVadim\r\nAlena\r\nOlya\r\nVanya\r\nBrus\r\nJohn\r\nAlice\r\n', 'output': ['16\r\nAlena\r\nAlexey\r\nAlice\r\nAndrey\r\nBrus\r\nDenis\r\nEgor\r\nJohn\r\nNikita\r\nOlya\r\nRomka\r\nSergey\r\nTaras\r\nUra\r\nVadim\r\nVanya\r\n']}, {'input': '6 6\r\nAlena\r\nOlya\r\nVanya\r\nBrus\r\nJohn\r\nAlice\r\nAlena John\r\nAlena Alice\r\nOlya John\r\nOlya Alice\r\nVanya John\r\nVanya Alice\r\n', 'output': ['4\r\nAlena\r\nBrus\r\nOlya\r\nVanya\r\n']}, {'input': '7 6\r\nAlena\r\nOlya\r\nVanya\r\nBrus\r\nJohn\r\nAlice\r\nMariana\r\nAlena John\r\nAlena Alice\r\nOlya John\r\nOlya Alice\r\nVanya John\r\nVanya Alice\r\n', 'output': ['5\r\nAlena\r\nBrus\r\nMariana\r\nOlya\r\nVanya\r\n']}, {'input': '1 0\r\nPetr\r\n', 'output': ['1\r\nPetr\r\n']}, {'input': '2 0\r\nNgzlPJgFgz\r\nQfpagVpWz\r\n', 'output': ['2\r\nNgzlPJgFgz\r\nQfpagVpWz\r\n']}, {'input': '2 1\r\ncLWdg\r\nGoWegdDRp\r\nGoWegdDRp cLWdg\r\n', 'output': ['1\r\nGoWegdDRp\r\n']}, {'input': '3 0\r\nr\r\nyVwqs\r\nsdTDerOyhp\r\n', 'output': ['3\r\nr\r\nsdTDerOyhp\r\nyVwqs\r\n']}, {'input': '3 3\r\nvRVatwL\r\nWmkUGiYEn\r\nuvvsXKXcJ\r\nWmkUGiYEn vRVatwL\r\nuvvsXKXcJ vRVatwL\r\nuvvsXKXcJ WmkUGiYEn\r\n', 'output': ['1\r\nWmkUGiYEn\r\n']}, {'input': '16 11\r\njA\r\nkyRNTE\r\neY\r\nToLcqN\r\nbnenhMxiK\r\nzlkOe\r\nXCKZ\r\neaQrds\r\nqUdInpi\r\nKgPQA\r\nmQIl\r\ninOCWEZHxy\r\nyA\r\nPIZRMOu\r\nXtueKFM\r\nfRNwNn\r\ninOCWEZHxy qUdInpi\r\nKgPQA zlkOe\r\ninOCWEZHxy KgPQA\r\nfRNwNn XCKZ\r\ninOCWEZHxy eY\r\nyA mQIl\r\ninOCWEZHxy ToLcqN\r\nyA KgPQA\r\nqUdInpi ToLcqN\r\nqUdInpi eaQrds\r\nPIZRMOu eY\r\n', 'output': ['10\r\nKgPQA\r\nPIZRMOu\r\nToLcqN\r\nXCKZ\r\nXtueKFM\r\nbnenhMxiK\r\neaQrds\r\njA\r\nkyRNTE\r\nmQIl\r\n']}, {'input': '12 12\r\njWuGgOjV\r\nWs\r\njTZQMyH\r\nULp\r\nUfsnPRt\r\nk\r\nbPKrnP\r\nW\r\nJOaQdgglDG\r\nAodc\r\ncpRjAUyYIW\r\nMrjB\r\nbPKrnP ULp\r\nk Ws\r\ncpRjAUyYIW k\r\nULp jTZQMyH\r\nbPKrnP jWuGgOjV\r\ncpRjAUyYIW jTZQMyH\r\nW ULp\r\nk jTZQMyH\r\nk ULp\r\nMrjB ULp\r\ncpRjAUyYIW Aodc\r\nW k\r\n', 'output': ['8\r\nAodc\r\nJOaQdgglDG\r\nMrjB\r\nUfsnPRt\r\nW\r\nWs\r\nbPKrnP\r\njTZQMyH\r\n']}, {'input': '11 17\r\njFTNgFBO\r\ntZDgmdF\r\nIjeDjoj\r\nBEMAaYkNb\r\nRZRQl\r\ntK\r\nlNHWt\r\nIdG\r\nLAbVLYiY\r\notOBsWqJuo\r\nUoTy\r\ntK BEMAaYkNb\r\nBEMAaYkNb jFTNgFBO\r\nIjeDjoj tZDgmdF\r\nRZRQl jFTNgFBO\r\nlNHWt tZDgmdF\r\nRZRQl tZDgmdF\r\nUoTy LAbVLYiY\r\nBEMAaYkNb IjeDjoj\r\nIdG BEMAaYkNb\r\nLAbVLYiY tK\r\nLAbVLYiY jFTNgFBO\r\nUoTy IjeDjoj\r\nlNHWt jFTNgFBO\r\nlNHWt BEMAaYkNb\r\ntK IjeDjoj\r\nUoTy RZRQl\r\nBEMAaYkNb tZDgmdF\r\n', 'output': ['6\r\nIdG\r\nIjeDjoj\r\nLAbVLYiY\r\nRZRQl\r\nlNHWt\r\notOBsWqJuo\r\n']}, {'input': '11 13\r\ncZAMfd\r\nSWQnweM\r\nKlQW\r\nWRsnNZT\r\nix\r\nUC\r\nLWqsVHcWec\r\nfeb\r\ncBy\r\ntvk\r\nRXDlX\r\nfeb SWQnweM\r\ncBy WRsnNZT\r\nLWqsVHcWec KlQW\r\nRXDlX feb\r\nLWqsVHcWec cZAMfd\r\ncBy UC\r\nWRsnNZT SWQnweM\r\nRXDlX cBy\r\ntvk UC\r\ncBy SWQnweM\r\nUC KlQW\r\nRXDlX KlQW\r\nUC WRsnNZT\r\n', 'output': ['6\r\nKlQW\r\nWRsnNZT\r\ncZAMfd\r\nfeb\r\nix\r\ntvk\r\n']}, {'input': '4 2\r\nadQx\r\nrJGeodBycK\r\ntgPYZk\r\ncz\r\ncz tgPYZk\r\nrJGeodBycK adQx\r\n', 'output': ['2\r\nadQx\r\ncz\r\n']}, {'input': '4 2\r\noVemoZhjW\r\nHspFEry\r\nhFO\r\njxt\r\nhFO HspFEry\r\njxt oVemoZhjW\r\n', 'output': ['2\r\nHspFEry\r\njxt\r\n']}, {'input': '5 2\r\niBrgNFlNXd\r\nlnGPIV\r\nnb\r\nB\r\nVgqRcEOG\r\nlnGPIV iBrgNFlNXd\r\nB iBrgNFlNXd\r\n', 'output': ['4\r\nB\r\nVgqRcEOG\r\nlnGPIV\r\nnb\r\n']}, {'input': '5 1\r\nWEYUdpYmZp\r\nfhNmMpjr\r\nydARivBg\r\ncilTtE\r\nyeXxkhPzB\r\nyeXxkhPzB cilTtE\r\n', 'output': ['4\r\nWEYUdpYmZp\r\ncilTtE\r\nfhNmMpjr\r\nydARivBg\r\n']}, {'input': '6 9\r\noySkmhCD\r\nUIKWj\r\nmHolKkBx\r\nQBikssqz\r\nZ\r\nzoFUJYa\r\nZ UIKWj\r\nQBikssqz oySkmhCD\r\nQBikssqz UIKWj\r\nZ oySkmhCD\r\nzoFUJYa UIKWj\r\nzoFUJYa Z\r\nzoFUJYa mHolKkBx\r\nzoFUJYa QBikssqz\r\nQBikssqz mHolKkBx\r\n', 'output': ['3\r\nUIKWj\r\nmHolKkBx\r\noySkmhCD\r\n']}, {'input': '6 1\r\nuPVIuLBuYM\r\nVejWyKCtbN\r\nqqjgF\r\nulBD\r\nDRNzxJU\r\nCOzbXWOt\r\nulBD qqjgF\r\n', 'output': ['5\r\nCOzbXWOt\r\nDRNzxJU\r\nVejWyKCtbN\r\nqqjgF\r\nuPVIuLBuYM\r\n']}, {'input': '7 14\r\nFXCT\r\nn\r\no\r\nS\r\nMdFuonu\r\nmszv\r\nbqScOCw\r\nS o\r\nbqScOCw FXCT\r\nMdFuonu o\r\no n\r\nbqScOCw n\r\nmszv S\r\nbqScOCw MdFuonu\r\nmszv n\r\nS FXCT\r\nbqScOCw o\r\no FXCT\r\nmszv MdFuonu\r\nmszv FXCT\r\nbqScOCw mszv\r\n', 'output': ['3\r\nFXCT\r\nMdFuonu\r\nn\r\n']}, {'input': '7 6\r\nj\r\nZ\r\nPZNeTyY\r\nm\r\na\r\nUj\r\nsuaaSiKcK\r\nUj PZNeTyY\r\na j\r\nPZNeTyY Z\r\nPZNeTyY j\r\nm PZNeTyY\r\nm j\r\n', 'output': ['5\r\nUj\r\nZ\r\na\r\nm\r\nsuaaSiKcK\r\n']}, {'input': '8 6\r\nU\r\nC\r\nPEElYwaxf\r\nVubTXNI\r\nJ\r\nIxZUHV\r\nhLNFnzmqFE\r\nDPPvwuWvmA\r\nhLNFnzmqFE IxZUHV\r\nIxZUHV C\r\nJ PEElYwaxf\r\nIxZUHV PEElYwaxf\r\nPEElYwaxf C\r\nJ VubTXNI\r\n', 'output': ['5\r\nC\r\nDPPvwuWvmA\r\nJ\r\nU\r\nhLNFnzmqFE\r\n']}, {'input': '8 12\r\nBkgxqAF\r\nKhq\r\nNpIfk\r\nkheqUyDVG\r\niRBkHlRpp\r\nZDaQY\r\nNG\r\nqN\r\nqN BkgxqAF\r\nNpIfk BkgxqAF\r\niRBkHlRpp BkgxqAF\r\niRBkHlRpp NpIfk\r\nNG Khq\r\niRBkHlRpp Khq\r\nNG ZDaQY\r\nNG iRBkHlRpp\r\nNG NpIfk\r\nqN Khq\r\nZDaQY kheqUyDVG\r\nNpIfk Khq\r\n', 'output': ['3\r\nBkgxqAF\r\nKhq\r\nZDaQY\r\n']}, {'input': '9 5\r\nRFiow\r\naxgvtiBGbx\r\ngGBVZtI\r\nVWAxrqx\r\nmnASVEQI\r\ntZHzWGAvXc\r\nBeaCYhIRLy\r\nhTdUL\r\nFJd\r\nhTdUL RFiow\r\nhTdUL gGBVZtI\r\nFJd axgvtiBGbx\r\nFJd BeaCYhIRLy\r\nhTdUL axgvtiBGbx\r\n', 'output': ['7\r\nBeaCYhIRLy\r\nRFiow\r\nVWAxrqx\r\naxgvtiBGbx\r\ngGBVZtI\r\nmnASVEQI\r\ntZHzWGAvXc\r\n']}, {'input': '9 13\r\nYiUXqlBUx\r\nQNgYuX\r\ndPtyZ\r\nITtwRJCv\r\nLJ\r\nrAG\r\nOgxNq\r\nsitechE\r\nvVAAz\r\nOgxNq QNgYuX\r\nOgxNq dPtyZ\r\nsitechE rAG\r\nLJ QNgYuX\r\nQNgYuX YiUXqlBUx\r\nOgxNq LJ\r\nvVAAz OgxNq\r\nrAG dPtyZ\r\nvVAAz LJ\r\nvVAAz ITtwRJCv\r\nsitechE LJ\r\nrAG YiUXqlBUx\r\nsitechE QNgYuX\r\n', 'output': ['4\r\nITtwRJCv\r\nLJ\r\nYiUXqlBUx\r\ndPtyZ\r\n']}, {'input': '9 6\r\nfLfek\r\nEQPcotnrp\r\nCaAlbwoIL\r\nVG\r\nNAZKIBiKT\r\noFy\r\njFluh\r\nKqHXRNya\r\nQSwgobA\r\noFy EQPcotnrp\r\nKqHXRNya jFluh\r\noFy NAZKIBiKT\r\njFluh oFy\r\njFluh fLfek\r\noFy fLfek\r\n', 'output': ['7\r\nCaAlbwoIL\r\nEQPcotnrp\r\nKqHXRNya\r\nNAZKIBiKT\r\nQSwgobA\r\nVG\r\nfLfek\r\n']}, {'input': '9 14\r\nmoRNeufngu\r\nBSKI\r\nzXl\r\ngwmIDluW\r\nYFn\r\nHvasEgl\r\nXcAC\r\neVP\r\nAiOm\r\neVP BSKI\r\neVP YFn\r\nHvasEgl YFn\r\neVP XcAC\r\nAiOm HvasEgl\r\nXcAC YFn\r\nzXl moRNeufngu\r\neVP zXl\r\nHvasEgl BSKI\r\nXcAC gwmIDluW\r\nXcAC HvasEgl\r\nYFn moRNeufngu\r\nzXl BSKI\r\nHvasEgl gwmIDluW\r\n', 'output': ['4\r\nAiOm\r\nBSKI\r\nYFn\r\ngwmIDluW\r\n']}, {'input': '15 8\r\ncXeOANpvBF\r\nbkeDfi\r\nnsEUAKNxQI\r\noSIb\r\naU\r\nXYXYVo\r\nduZQ\r\naPkr\r\nPVrHpL\r\nmVgmv\r\nhHhukllwbf\r\nGkNPGYVxjY\r\nbgBjA\r\nslNKCLIlOv\r\nmPILXy\r\nbgBjA cXeOANpvBF\r\nGkNPGYVxjY cXeOANpvBF\r\nslNKCLIlOv GkNPGYVxjY\r\nGkNPGYVxjY mVgmv\r\nXYXYVo cXeOANpvBF\r\nslNKCLIlOv bkeDfi\r\nmVgmv aPkr\r\nslNKCLIlOv nsEUAKNxQI\r\n', 'output': ['12\r\nGkNPGYVxjY\r\nPVrHpL\r\nXYXYVo\r\naPkr\r\naU\r\nbgBjA\r\nbkeDfi\r\nduZQ\r\nhHhukllwbf\r\nmPILXy\r\nnsEUAKNxQI\r\noSIb\r\n']}, {'input': '15 3\r\na\r\nYclKFJoaIA\r\nhalYcB\r\nbLOlPzAeQ\r\ntckjt\r\noDFijpx\r\nb\r\npz\r\nVDLb\r\nlCEHPibt\r\noF\r\npzJD\r\nMC\r\nqklsX\r\nTAU\r\npzJD tckjt\r\nqklsX oF\r\nMC pzJD\r\n', 'output': ['13\r\nMC\r\nTAU\r\nVDLb\r\nYclKFJoaIA\r\na\r\nb\r\nbLOlPzAeQ\r\nhalYcB\r\nlCEHPibt\r\noDFijpx\r\noF\r\npz\r\ntckjt\r\n']}, {'input': '16 8\r\nJIo\r\nINanHVnP\r\nKaxyCBWt\r\nkVfnsz\r\nRAwFYCrSvI\r\nF\r\nvIEWWIvh\r\nTGF\r\nFeuhJJwJ\r\nTngcmS\r\nSqI\r\nRmcaVngp\r\neGwhme\r\nlwaFfXzM\r\noabGmpvVH\r\nTMT\r\nFeuhJJwJ F\r\neGwhme FeuhJJwJ\r\nRmcaVngp SqI\r\nINanHVnP JIo\r\nSqI FeuhJJwJ\r\nF kVfnsz\r\nTGF F\r\nTMT TGF\r\n', 'output': ['11\r\nF\r\nINanHVnP\r\nKaxyCBWt\r\nRAwFYCrSvI\r\nRmcaVngp\r\nTMT\r\nTngcmS\r\neGwhme\r\nlwaFfXzM\r\noabGmpvVH\r\nvIEWWIvh\r\n']}, {'input': '16 25\r\nbBZ\r\nEr\r\nZ\r\nrYJmfZLgmx\r\nPaJNrF\r\naHtRqSxOO\r\nD\r\nhsagsG\r\nMDuBOXrmWH\r\nSgjMQZ\r\nYXgWq\r\nxDwpppG\r\nSDY\r\nJwZWx\r\ncOzrgrBaE\r\nFJYX\r\nYXgWq SgjMQZ\r\nSDY PaJNrF\r\nFJYX rYJmfZLgmx\r\nhsagsG Er\r\nxDwpppG rYJmfZLgmx\r\naHtRqSxOO rYJmfZLgmx\r\nhsagsG bBZ\r\nJwZWx hsagsG\r\nFJYX cOzrgrBaE\r\nSDY YXgWq\r\nFJYX Z\r\nJwZWx rYJmfZLgmx\r\nD rYJmfZLgmx\r\nYXgWq Z\r\nrYJmfZLgmx Z\r\naHtRqSxOO bBZ\r\nSDY rYJmfZLgmx\r\ncOzrgrBaE D\r\nYXgWq hsagsG\r\nSDY aHtRqSxOO\r\ncOzrgrBaE xDwpppG\r\nSDY bBZ\r\nSDY Er\r\nJwZWx xDwpppG\r\nFJYX JwZWx\r\n', 'output': ['8\r\nD\r\nEr\r\nJwZWx\r\nMDuBOXrmWH\r\nPaJNrF\r\nSgjMQZ\r\nZ\r\naHtRqSxOO\r\n']}, {'input': '16 37\r\ntIWi\r\nq\r\nIEAYCq\r\nXozwkum\r\nCC\r\niPwfd\r\nS\r\nXEf\r\nWqEiwkH\r\nWX\r\ne\r\nltmruh\r\nKGx\r\nauTUYZRC\r\nmeJa\r\nM\r\nmeJa q\r\nKGx e\r\nXEf Xozwkum\r\ne q\r\nauTUYZRC KGx\r\ne CC\r\nM CC\r\nM meJa\r\nWX CC\r\nWqEiwkH IEAYCq\r\nauTUYZRC WqEiwkH\r\nKGx WX\r\nmeJa KGx\r\nXEf q\r\nauTUYZRC XEf\r\nauTUYZRC IEAYCq\r\nWX XEf\r\nM XEf\r\nWqEiwkH q\r\nM KGx\r\nKGx CC\r\nM e\r\nWqEiwkH Xozwkum\r\nCC q\r\nS Xozwkum\r\nKGx tIWi\r\nWX q\r\nXEf S\r\nauTUYZRC S\r\nCC IEAYCq\r\nKGx IEAYCq\r\ne WqEiwkH\r\nM S\r\nauTUYZRC q\r\nS tIWi\r\nM ltmruh\r\nM iPwfd\r\n', 'output': ['8\r\nIEAYCq\r\nWX\r\nXozwkum\r\ne\r\niPwfd\r\nltmruh\r\nmeJa\r\ntIWi\r\n']}, {'input': '16 11\r\ntulhZxeKgo\r\nbrAXY\r\nyQUkaihDAg\r\nmwjlDVaktK\r\nweVtBIP\r\nzRwb\r\nds\r\nhXPfJrL\r\nAdIfP\r\nazQeXn\r\nB\r\nJlmscIUOxO\r\nZuxr\r\nV\r\nOfyLIUO\r\nuaMl\r\nhXPfJrL yQUkaihDAg\r\nweVtBIP yQUkaihDAg\r\nazQeXn hXPfJrL\r\nV tulhZxeKgo\r\nzRwb yQUkaihDAg\r\nds mwjlDVaktK\r\nzRwb brAXY\r\nyQUkaihDAg brAXY\r\nB yQUkaihDAg\r\nAdIfP mwjlDVaktK\r\nbrAXY tulhZxeKgo\r\n', 'output': ['11\r\nAdIfP\r\nB\r\nJlmscIUOxO\r\nOfyLIUO\r\nV\r\nZuxr\r\nazQeXn\r\nbrAXY\r\nds\r\nuaMl\r\nweVtBIP\r\n']}, {'input': '5 10\r\nTaras\r\nNikita\r\nSergey\r\nAndrey\r\nRomka\r\nTaras Romka\r\nTaras Nikita\r\nTaras Sergey\r\nTaras Andrey\r\nRomka Nikita\r\nRomka Sergey\r\nRomka Andrey\r\nNikita Sergey\r\nNikita Andrey\r\nSergey Andrey\r\n', 'output': ['1\r\nAndrey\r\n']}]


import collections
l=list(input())
p=list(input())
#print(p)
#print(l)
cl=collections.Counter(l)
pl=collections.Counter(p)
#print(cl)
#print(pl)
plk=list(pl.keys())
print(plk)
if ' ' in plk:
    plk.remove(' ')
else:
    pass
n=len(plk)
i=0
er=0
#print(cl['s'])
while i<n:
    h=plk[i]
    t=cl[h]
    q=pl[h]
    #print(t)
    #print(q)
    if t>=q:
        er+=1
    else:
        pass
    i+=1
#print(n)
#print(er)
if er==n:
    print('YES')

else:
    print('NO')

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

The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.

If Vasya can write the given anonymous letter, print YES, otherwise print NO

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

import collections
l=list(input())
p=list(input())
#print(p)
#print(l)
cl=collections.Counter(l)
pl=collections.Counter(p)
#print(cl)
#print(pl)
plk=list(pl.keys())
#print(plk)
if ' ' in plk:
    plk.remove(' ')
else:
    pass
n=len(plk)
i=0
er=0
#print(cl['s'])
while i<n:
    h=plk[i]
    t=cl[h]
    q=pl[h]
    #print(t)
    #print(q)
    if t>=q:
        er+=1
    else:
        pass
    i+=1
#print(n)
#print(er)
if er==n:
    print('YES')

else:
    print('NO')

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


# prob B

n = input()
seq = raw_input()

seq = [int(i) for i in seq.split()]
seq.sort()

tot = 0
for i, j in zip(seq, range(1, n+1)):
    if i != j:
        tot += 1

print tot

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

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

# prob B

n = input()
seq = raw_input()

seq = [int(i) for i in seq.split()]
seq.sort()

tot = 0
right_seq = range(1, n+1)
for num in seq:
    if num in right_seq:
        right_seq.remove(num)
    else:
        tot += 1

print tot


#_________________ Mukul Mohan Varshney _______________#

#Template
import sys
import os
import math
import copy
from math import gcd
from bisect import bisect
from io import BytesIO, IOBase
from math import sqrt,floor,factorial,gcd,log,ceil
from collections import deque,Counter,defaultdict
from itertools import permutations, combinations

#define function
def Int(): return int(sys.stdin.readline())
def Mint(): return map(int,sys.stdin.readline().split())
def Lstr(): return list(sys.stdin.readline().strip())
def Str(): return sys.stdin.readline().strip()
def Mstr(): return map(str,sys.stdin.readline().strip().split())
def List(): return list(map(int,sys.stdin.readline().split()))
def Hash(): return dict()
def Mod(): return 1000000007
def Ncr(n,r,p): return ((fact[n])*((ifact[r]*ifact[n-r])%p))%p
def Most_frequent(list): return max(set(list), key = list.count)
def Mat2x2(n): return [List() for _ in range(n)]
def btod(n):
    return int(n,2)

def dtob(n):
    return bin(n).replace("0b","")

# Driver Code
def solution():
     #for _ in range(Int()):
          n,t=Mint()
          ans=[]
          for i in range(n):
               x,y=Mint()
               ans.append([2*x-y,2*x+y])
          mukul=2
          ans.sort()
          for i in range(1,len(ans)):

               res=(ans[i][0]-ans[i-1][1])
               print(res)
               if(res>2*t):
                    mukul+=2
               elif(res==2*t):
                    mukul+=1
          print(mukul)

#Call the solve function
if __name__ == "__main__":

     solution()

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

The first line of the input data contains numbers n and t (1 ≤ n, t ≤ 1000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi — x-coordinate of the centre of the i-th house, and ai — length of its side ( - 1000 ≤ xi ≤ 1000, 1 ≤ ai ≤ 1000).

Output the amount of possible positions of the new house.

NoteIt is possible for the x-coordinate of the new house to have non-integer value.

#15A - Cottage Village
# n - how many square houses we have on the x-axis
# t - the side of the main house
n, t = map(int, input().split())
#Variable that sorts square houses by x-axis coordinates in ascending order
#Input: house's center on the x-axis and the house's side length
houses = sorted([list(map(int, input().split())) for i in range(n)], key=lambda x: x[0])
#Because there's at least 1 other house in the village, we have 2 possibilities
#by default, cause the main house can touch one of the 2 exposed sides of the other house
ans = 2
#The next loop computes the number of houses that fit between 2 adjacent houses
for i in range(n - 1):
    x = houses[i][0] + houses[i][1] / 2
    y = houses[i + 1][0] - houses[i + 1][1] / 2
    #If the space between the 2 houses is equal to the main house's side,
    #the only way we can place our house is to touch both houses at the same time
    if y - x == t:
        ans += 1
    #If the space between the houses is bigger than the main house's side,
    #then we consider the 2 houses as 2 separate cases, each with 2 possibilities
        #of their own
    elif y - x > t:
        ans += 2

print(ans)


"""
Peter likes to travel by train. He likes it so much that on the train he falls asleep.

Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.

The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.

At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.

Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.

Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.

The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output
Output one of the four words without inverted commas:

«forward» — if Peter could see such sequences only on the way from A to B;
«backward» — if Peter could see such sequences on the way from B to A;
«both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
«fantasy» — if Peter could not see such sequences.
"""

x = input()
x_reversed = ''.join(list(reversed(x)))

seq1 = input()
seq2 = input()

if len(seq1) + len(seq2) > len(x): # if sum of peter's colors exceed the whole number of colors
	print('fantasy')
else:
	forward = False
	backward = False

	if seq1 in x:
		if seq2 in x[x.find(seq1) + len(seq1):]
			forward = True

	if seq1 in x_reversed:
		if seq2 in x_reversed[x_reversed.find(seq1) + len(seq1):]
			backward = True

	if forward and backward:
		print('both')
	elif forward:
		print("forward")
	elif backward:
		print("backward")
	else:
		print('fantasy')

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

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

"""
Peter likes to travel by train. He likes it so much that on the train he falls asleep.

Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.

The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.

At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.

Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.

Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.

The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output
Output one of the four words without inverted commas:

«forward» — if Peter could see such sequences only on the way from A to B;
«backward» — if Peter could see such sequences on the way from B to A;
«both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
«fantasy» — if Peter could not see such sequences.
"""

x = input()
x_reversed = ''.join(list(reversed(x)))

# print(x)
# print(x_reversed)

seq1 = input()
seq2 = input()

if len(seq1) + len(seq2) > len(x):
	print('fantasy')
else:
	forward = False
	backward = False

	x_find_seq1 = x.find(seq1)
	if x_find_seq1 > -1:
		x_find_seq2 = x[x_find_seq1 + len(seq1):].find(seq2)
		if x_find_seq2 > -1:
			x_find_seq2 += x_find_seq1 + len(seq1)
	else:
		x_find_seq2 = -1

	x_reversed_find_seq1 = x_reversed.find(seq1)
	if x_reversed_find_seq1 > -1:
		x_reversed_find_seq2 = x_reversed[x_reversed_find_seq1 + len(seq1):].find(seq2)
		if x_reversed_find_seq2 > -1:
			x_reversed_find_seq2 += x_reversed_find_seq1 + len(seq1)
	else:
		x_reversed_find_seq2 = -1

	# print('x_find_seq1:', x_find_seq1)
	# print('x_find_seq2:', x_find_seq2)

	# print("--------")
	# print(x_reversed)
	# print('x_reversed_find_seq1:', x_reversed_find_seq1)
	# print('x_reversed_find_seq2:', x_reversed_find_seq2)

	if (x_find_seq1 != -1 and x_find_seq1 != -1):
		if x_find_seq1 <= x_find_seq2:
			forward = True

	if (x_reversed_find_seq1 != -1 and x_reversed_find_seq1 != -1):
		if x_reversed_find_seq1 <= x_reversed_find_seq2:
			backward = True

	if forward and backward:
		print('both')
	elif forward:
		print("forward")
	elif backward:
		print("backward")
	else:
		print('fantasy')

"""
x = [1,2,3,4]
print(x[1:])

seq1_list = list(seq1)
seq1_len = len(seq1)

seq2_list = list(seq2)
seq2_len = len(seq2)

x_len = len(x)

seq1_found = False
for elm, i in enumerate(x):
	if elm == seq1_list[0] and x_len-i >= seq1_len:
		for j in seq2_list:
			if j !=
"""

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


n = int(input())

coodenadas = []
for i in range(n):
    x, y = [ int(i) for i in input().split() ]
    coodenadas.append([x, y, {
        'x': { x },
        'y': { y }
    }])

aux = 0
for i in range(n):
    j = i + 1
    grafo = coodenadas[i][2]
    while j < len(coodenadas):
        x = coodenadas[j][0]
        y = coodenadas[j][1]
        if j != i and (x in grafo['x'] or y in grafo['y']):
            aux += 1
            grafo['x'].add(x)
            grafo['y'].add(y)
            coodenadas[j][2] = grafo
        j += 1

print(n - aux - 1)

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

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

n = int(input())

coodenadas = []
for i in range(n):
    x, y = [ int(i) for i in input().split() ]
    coodenadas.append({
        'x': { x },
        'y': { y }
    })

for i in range(n-1, -1, -1):
    j = i - 1
    while j >= 0 and i < len(coodenadas):
        if len(coodenadas[j]['x'].intersection(coodenadas[i]['x'])) or len(coodenadas[j]['y'].intersection(coodenadas[i]['y'])):
            coodenadas[i]['x'].update(coodenadas[j]['x'])
            coodenadas[i]['y'].update(coodenadas[j]['y'])
            coodenadas.pop(j)
        j -= 1

print(len(coodenadas) - 1)


n=int(input())
a=list(map(int,input().split()))
ans=1e9
for i in range(n-1):
    ans=min(ans,max(a[i],a[i+1]))
print(ans)

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

The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles. The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).

Print a single number — the sought number of days.

NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.

n=int(input())
a=list(map(int,input().split()))
ans=1e9
for i in range(n-1):
    ans=min(ans,max(a[i],a[i+1]))
print(min(ans,a[0],a[-1]))


from math import *

class graph:
    # initialize graph
    def __init__(self, gdict=None):
        if gdict is None:
            gdict = dict({})
        self.gdict = gdict

    # get edges
    def edges(self):
        return self.find_edges()

    # find edges
    def find_edges(self):
        edges = []
        for node in self.gdict:
            for nxNode in self.gdict[node]:
                if {nxNode, node} not in edges:
                    edges.append({node, nxNode})
        return edges

    # Get verticies
    def get_vertices(self):
        return list(self.gdict.keys())

    # add vertix
    def add_vertix(self, node):
        if node not in self.gdict:
            self.gdict[node] = []

    # add edge
    def add_edge(self, edge):
        edge = set(edge)
        (node1, node2) = edge
        if node1 in self.gdict:
            self.gdict[node1].append(node2)
        else:
            self.gdict[node1] = [node2]

        if node2 in self.gdict:
            self.gdict[node2].append(node1)
        else:
            self.gdict[node2] = [node1]

def inp():
    return map(int, input().split())

def arr_inp():
    return [int(x) for x in input().split()]

n, m = inp()
a = arr_inp()
g = graph()
cost = inf

for i in range(m):
    u, v = inp()
    g.add_edge((u, v))
    if (i > 1):
        for key in g.gdict:
            if (u in g.gdict[key] and v in g.gdict[key]):
                cost = min(cost, u + v + int(key))

if (cost == inf):
    print(-1)
else:
    print(cost)

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

The first input file line contains integers n and m — the total number of clothing items in the shop and the total number of matching pairs of clothing items (). Next line contains n integers ai (1 ≤ ai ≤ 106) — the prices of the clothing items in rubles. Next m lines each contain a pair of space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi). Each such pair of numbers means that the ui-th and the vi-th clothing items match each other. It is guaranteed that in each pair ui and vi are distinct and all the unordered pairs (ui, vi) are different.

Print the only number — the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes).

NoteIn the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way — to buy the 3 pieces of clothing; in this case he spends 6 roubles.The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1.In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1.

import itertools
import math

import time
def timer(f):
    def tmp(*args, **kwargs):
        t = time.time()
        res = f(*args, **kwargs)
        print("Время выполнения функции: %f" % (time.time()-t))
        return res

    return tmp

#n = int(input())

n, m = map(int, input().split(' '))
array = list(map(int, input().split(' ')))
matrix = [[0 for j in range(n)] for i in range(n)]
for i in range(m):
    a, b = map(int, input().split(' '))
    a-=1
    b-=1
    matrix[a][b] = 1
    matrix[b][a] = 1

price = 100000000000000
u = 0;
uu = 0;
uuu = 0;
for i in range(n):
    for j in range(n):
        for k in range(n):
            if i!=j and j!=k and i!=k:
                if matrix[i][j]==1 and matrix[i][k]==1 and matrix[j][k]==1:
                    cp = array[i]+array[j]+array[k]
                    if cp<price:
                        price = cp
                        u = i
                        uu = j
                        uuu = k
                else:
                    #print(i, j, k)
                    pass

if price == 100000000000000:
    print(-1)
else:
    print(price)


def c(count):
	for i in count:
		if i!=0:
			return True
	return False
n,m=map(int,raw_input().split())
dic={}
count=[0]
for i in range(1,n+1):
	dic[i]=[]
	count.append(0)
for i  in range(m):
	a,b,=map(int,raw_input().split())
	count[a] = count[a]+1
	count[b] = count[b]+1
	dic[a].append(b)
	dic[b].append(a)
# print count
j=5
Flag=True
ans=0
import copy
count_1 = copy.copy(count)
while c(count_1):
	Flag=False
	count=copy.copy(count_1)
	for i in range(1,n+1):
		if c(count_1) and count[i]==1:
			Flag=True
			count_1[i]=count_1[i]-1
			count_1[dic[i][0]] = count_1[dic[i][0]]-1
			dic[dic[i][0]].remove(i)
			dic[i].pop(0)
	if not Flag:
		break
	ans=ans+1
	# print count
print ans

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

The first line contains two integers n and m — the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b — the numbers of students tied by the i-th lace (1 ≤ a, b ≤ n, a ≠ b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.

Print the single number — the number of groups of students that will be kicked out from the club.

NoteIn the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.

r = lambda: raw_input().strip()

n,m = map(int,r().split())
ties = [map(int,r().split()) for _ in xrange(m)]
count = 0
while len(ties)>0:
    all_ties = []
    l1 = len(ties)
    for t in ties:
        all_ties.append(t[0])
        all_ties.append(t[1])
    for i in xrange(n):
        if all_ties.count(i+1)==1:
            for t in xrange(len(ties)):
                if ties[t][0] == i+1 or ties[t][1] == i+1:
                    ties.remove(ties[t])
                    break
    l2 = len(ties)
    if l1==l2:
        break
    count += 1
print count


import math
n=int(input())
l=list(map(int,input().split()))
d=0
diff=l[n-1]-l[0]
o1,o2=n,1
for i in range(n-1):
    d=abs(l[i+1]-l[i])
    if d<diff:
        diff=d
        o1=i+1
        o2=i+2
print(o1,o2)

n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.

The first line contains integer n (2 ≤ n ≤ 100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000). The soldier heights are given in clockwise or counterclockwise direction.

Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.

n = int(input())
l = list(map(int,input().split()))
l.append(l[0])
# print(l)
m = abs(l[1]-l[0])
# print(m)
a = 1
for i in range(2,n+1):
    if(abs(l[i]-l[i-1]))<m:
        # print(abs(l[i]-l[i-1])
        m = abs(l[i]-l[i-1])
        a = i
if(a==n):
    print(a,1)
else:
    print(a,a+1)


class Piet:
    inc = [{'x':0,'y':-1},{'x':1,'y':0},{'x':0,'y':1},{'x':-1,'y':0}]
    def __init__(self):
        self.BP = {'x':0,'y':0}
        self.DP = 1
        self.CP = 0
        self.getdata()
        self.go()
    def getdata(self):
        in_line = raw_input().split()
        self.m = int(in_line[0])
        self.n = int(in_line[1])
        self.pixels = []
        for i in range(self.m):
            self.pixels.append(raw_input())
    def is_out_limit(self,x,y):
        if x >= len(self.pixels[0]) or y >= self.m or x<0 or y<0:
            return True
        else:
            return False
    def go(self):
        ans = []
        for t in range(self.n):
            print(self.BP['x'],self.BP['y'],self.DP,self.CP)
            while True:
                if self.is_out_limit(self.BP['x']+Piet.inc[self.DP]['x'],self.BP['y']+Piet.inc[self.DP]['y']):
                    break
                curr_color = self.pixels[self.BP['y']][self.BP['x']]
                new_color = self.pixels[self.BP['y']+Piet.inc[self.DP]['y']][self.BP['x']+Piet.inc[self.DP]['x']]
                if curr_color == new_color:
                    self.BP['x'] += Piet.inc[self.DP]['x']
                    self.BP['y'] += Piet.inc[self.DP]['y']
                else:
                    break
            while True:
                if self.is_out_limit(self.BP['x']+Piet.inc[self.CP]['x'],self.BP['y']+Piet.inc[self.CP]['y']):
                    break
                curr_color = self.pixels[self.BP['y']][self.BP['x']]
                new_color = self.pixels[self.BP['y']+Piet.inc[self.CP]['y']][self.BP['x']+Piet.inc[self.CP]['x']]
                if curr_color == new_color:
                    self.BP['x'] += Piet.inc[self.CP]['x']
                    self.BP['y'] += Piet.inc[self.CP]['y']
                else:
                    break
            if  self.is_out_limit(self.BP['x']+Piet.inc[self.DP]['x'],self.BP['y']+Piet.inc[self.DP]['y']) or self.pixels[self.BP['y']+Piet.inc[self.DP]['y']][self.BP['x']+Piet.inc[self.DP]['x']] == '0':
                if self.DP == (self.CP + 1)%4:
                    self.CP = (self.CP + 2)%4
                else:
                    self.DP = (self.DP + 1)%4
                    self.CP = (self.DP - 1)%4
            else:
                self.BP['x'] += Piet.inc[self.DP]['x']
                self.BP['y'] += Piet.inc[self.DP]['y']
            if self.BP['x'] == fBPx and self.BP['y'] == fBPy and self.DP == fDP and self.CP ==fCP:
                print ans[(self.n-1)%len(ans)]
                break
            else:
                if len(ans) == 0:
                    fBPx = self.BP['x']
                    fBPy = self.BP['y']
                    fDP = self.DP
                    fCP = self.CP
                ans.append(self.pixels[self.BP['y']][self.BP['x']])
        else:
            print ans[-1]

def main():
    p = Piet()

if __name__ == '__main__':
    main()

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.

class Piet:
    inc = [{'x':0,'y':-1},{'x':1,'y':0},{'x':0,'y':1},{'x':-1,'y':0}]
    def __init__(self):
        self.BP = {'x':0,'y':0}
        self.DP = 1
        self.CP = 0
        self.getdata()
        self.go()
    def getdata(self):
        in_line = raw_input().split()
        self.m = int(in_line[0])
        self.n = int(in_line[1])
        self.pixels = []
        for i in range(self.m):
            self.pixels.append(raw_input())
    def is_out_limit(self,x,y):
        if x >= len(self.pixels[0]) or y >= self.m or x<0 or y<0:
            return True
        else:
            return False
    def go(self):
        ans = []
        info = []
        for t in xrange(self.n):
            while True:
                if self.is_out_limit(self.BP['x']+Piet.inc[self.DP]['x'],self.BP['y']+Piet.inc[self.DP]['y']):
                    break
                curr_color = self.pixels[self.BP['y']][self.BP['x']]
                new_color = self.pixels[self.BP['y']+Piet.inc[self.DP]['y']][self.BP['x']+Piet.inc[self.DP]['x']]
                if curr_color == new_color:
                    self.BP['x'] += Piet.inc[self.DP]['x']
                    self.BP['y'] += Piet.inc[self.DP]['y']
                else:
                    break
            while True:
                if self.is_out_limit(self.BP['x']+Piet.inc[self.CP]['x'],self.BP['y']+Piet.inc[self.CP]['y']):
                    break
                curr_color = self.pixels[self.BP['y']][self.BP['x']]
                new_color = self.pixels[self.BP['y']+Piet.inc[self.CP]['y']][self.BP['x']+Piet.inc[self.CP]['x']]
                if curr_color == new_color:
                    self.BP['x'] += Piet.inc[self.CP]['x']
                    self.BP['y'] += Piet.inc[self.CP]['y']
                else:
                    break
            if  self.is_out_limit(self.BP['x']+Piet.inc[self.DP]['x'],self.BP['y']+Piet.inc[self.DP]['y']) or self.pixels[self.BP['y']+Piet.inc[self.DP]['y']][self.BP['x']+Piet.inc[self.DP]['x']] == '0':
                if self.DP == (self.CP + 1)%4:
                    self.CP = (self.CP + 2)%4
                else:
                    self.DP = (self.DP + 1)%4
                    self.CP = (self.DP - 1)%4
            else:
                self.BP['x'] += Piet.inc[self.DP]['x']
                self.BP['y'] += Piet.inc[self.DP]['y']
            #print(self.BP['x'],self.BP['y'],self.DP,self.CP)
            if (self.BP['x'],self.BP['y'],self.DP,self.CP) in info:
                dot = info.index( (self.BP['x'],self.BP['y'],self.DP,self.CP) )
                print ans[dot-1+(self.n-dot)%(len(ans)-dot)]
                break
            else:
                ans.append(self.pixels[self.BP['y']][self.BP['x']])
                info.append( (self.BP['x'],self.BP['y'],self.DP,self.CP) )
        else:
            print ans[-1]

def main():
    p = Piet()

if __name__ == '__main__':
    main()


def primes(n):
    pr = range(n)
    for i in xrange(2,n):
        if not pr[i]: continue
        ii=i*i
        if ii>n: break
        pr[ii::i]=[0]*len(pr[ii::i])
    return filter(None,pr)[1:]

n,x = map(int,raw_input().split())
a = set(map(int,raw_input().split()))
pr = primes(x)
if all(p in a for p in pr): print len(pr)
else: print -1

Vasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than x and not less than 2 items in his inventory. A new patch for the game appeared to view inventory in n different modes. Displaying in mode i is a partition of all inventory items on pages, each of which (except for maybe the last one) shows exactly ai items. In addition, each mode shows how many pages bi is in a complete list. Great! Perhaps this information will be enough for Vasya to find the required number. Moreover, it is very interesting, what is the fewest number of modes in which Vasya can see inventory to determine the number of items in it?Vasya cannot use the information that was received while looking on inventory in some mode for selection of next actions. I. e. Vasya chooses some set of modes first, and then sees all the results and determines the size.Knowing the number of ai, x and assuming that Vasya is very smart, check whether he can uniquely determine the number of items in his inventory, and how many modes he will need to do that if he knows numbers ai, x and he is able to know number bi after viewing items in mode i.

The first line contains two integers n and x (0 ≤ n ≤ 105, 2 ≤ x ≤ 109). The second line contains integers ai (1 ≤ ai ≤ 109). Some numbers among all ai may be equal.

Output the fewest amount of modes required to uniquely determine amount of items in the inventory. If there is no solution output  - 1.

NoteIn the second example Vasya is not able to determine items count uniquely because 3 items, as well as 4 items, can be displayed on two pages.

n,x = map(int,raw_input().split())
a = set(map(int,raw_input().split()))
if 1 in a and x>2: print 1
elif x>1300000: print -1
else:
    pr = range(x)
    for i in xrange(2,x):
        if not pr[i]: continue
        ii=i*i
        if ii>x: break
        pr[ii::i]=[0]*len(pr[ii::i])
    pr = set(filter(None,pr)[1:])
    print -1 if len(pr-a) else len(pr)


N, M = [int(w) for w in input().split()]
graph = [[] for _ in range(N)]
dp = [[0] * (2 ** N) for _ in range(N)]

self_circles = 0

for _ in range(M):
    a, b = [int(w) - 1 for w in input().split()]
    if a == b:
        self_circles += 1
    else:
        graph[a].append(b)
        graph[b].append(a)

for i in range(N):
    dp[i][1 << i] = 1

result = -M
for i in range(2 ** N):
    for j in range(N):
        if dp[j][i] == 0:
            continue
        for k in graph[j]:
            mask_k = 2 ** k
            if mask_k < (i & (-i)):
                continue
            if mask_k & i > 0:
                if mask_k == i & (- i):
                    result += dp[j][i]
            else:
                dp[k][i | mask_k] += dp[j][i]

print(result//2)

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.

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

import bisect
import copy
import heapq
import sys
from types import GeneratorType
from functools import cmp_to_key
from collections import defaultdict, Counter, deque
import math
from math import inf
from functools import lru_cache
from heapq import nlargest
from functools import reduce
import random
from itertools import combinations
from operator import xor, add
from operator import mul
from typing import List, Dict, Set, Tuple, DefaultDict
from random import randint
from operator import or_

INF = float("inf")
BIG = int(1e32)
RANDOM = randint(1, 10 ** 9)

class FastIO:
    def __init__(self):
        return

    @staticmethod
    def _read():
        return sys.stdin.readline().strip()

    def read_int(self):
        return int(self._read())

    def read_float(self):
        return float(self._read())

    def read_ints(self):
        return map(int, self._read().split())

    def read_floats(self):
        return map(float, self._read().split())

    def read_ints_minus_one(self):
        return map(lambda x: int(x) - 1, self._read().split())

    def read_list_ints(self):
        return list(map(int, self._read().split()))

    def read_list_floats(self):
        return list(map(float, self._read().split()))

    def read_list_ints_minus_one(self):
        return list(map(lambda x: int(x) - 1, self._read().split()))

    def read_str(self):
        return self._read()

    def read_list_strs(self):
        return self._read().split()

    def read_list_str(self):
        return list(self._read())

    @staticmethod
    def st(x):
        return sys.stdout.write(str(x) + '\n')

    @staticmethod
    def lst(x):
        return sys.stdout.write(" ".join(str(w) for w in x) + '\n')

    @staticmethod
    def round_5(f):
        res = int(f)
        if f - res >= 0.5:
            res += 1
        return res

    @staticmethod
    def max(*args):
        res = args[0]
        for b in args[1:]:
            res = res if res > b else b
        return res

    @staticmethod
    def min(*args):
        res = args[0]
        for b in args[1:]:
            res = res if res < b else b
        return res

    @staticmethod
    def bootstrap(f, queue=[]):
        def wrappedfunc(*args, **kwargs):
            if queue:
                return f(*args, **kwargs)
            else:
                to = f(*args, **kwargs)
                while True:
                    if isinstance(to, GeneratorType):
                        queue.append(to)
                        to = next(to)
                    else:
                        queue.pop()
                        if not queue:
                            break
                        to = queue[-1].send(to)
                return to

        return wrappedfunc

    def ask(self, lst):
        self.lst(lst)
        sys.stdout.flush()
        res = self.read_int()
        return res

class Wrapper(int):
    # ç¨æ¥è§é¿ py åå¸ç¢°æçé®é¢åè¿è¡å é
    def __init__(self, x):
        int.__init__(x)
        # åçæ¯å¼æä¸ä¸ªéæºç§å

    def __hash__(self):
        # ä¹å¯ä»¥å°æ°ç»æåºåè¿è¡åå¸è®¡æ°
        return super(Wrapper, self).__hash__() ^ RANDOM

class Solution:
    def __init__(self):
        return

    @staticmethod
    def main(ac=FastIO()):
        n, m = ac.read_ints()

        # å»ºå¾
        dct = [[] for _ in range(n)]
        for _ in range(m):
            i, j = ac.read_ints_minus_one()
            dct[i].append(j)
            dct[j].append(i)

        # åå§å
        dp = [[0] * n for _ in range(1 << n)]
        for i in range(n):
            dp[1 << i][i] = 1

        ans = 0
        for i in range(1, 1 << n):  # ç»è¿çç¹ç¶æï¼lowest_bitä¸ºèµ·ç¹
            for j in range(n):
                if not dp[i][j]:
                    continue
                for k in dct[j]:
                    # ä¸ä¸è·³å¿é¡»ä¸è½æ¯èµ·ç¹åºå·å°
                    if (i & -i) > (1 << k):
                        continue
                    if i & (1 << k):
                        # è®¿é®è¿ä¸æ¯èµ·ç¹åå½¢æç¯
                        if (i & -i) == 1 << k:
                            ans += dp[i][j]
                    else:
                        # æªè®¿é®è¿ä¼ å°ä¸ä¸ç¶æ
                        dp[i ^ (1 << k)][k] += dp[i][j]

        # å»é¤ä¸æ¡è¾¹çç¯ä»¥åæ¯æ åå¾éè¦é¤ä»¥äº
        ans = (ans - m) // 2
        ac.st(ans)
        return

Solution().main()


from sys import stdin
input = stdin.readline

inp = lambda : list(map(int,input().split()))

def b_s(key , i):

    l , h = 0 , len(pos[i]) - 1
    ans = len(pos[i])
    while(l <= h):

        mid = (l + h) // 2
        if(a[mid] < key):
            l = mid + 1
        else:
            ans = mid
            h = mid - 1

    return ans

def solve(mask):

    if(mask == (1 << 20) - 1):return 0
    if(dp[mask] != -1):return dp[mask]

    p = 0
    for j in range(20):
        if(mask >> j & 1):
            p += len(pos[j])

    ans = float('inf')
    for j in range(20):
        if(mask >> j & 1):continue

        x = len(pos[j])
        ind = b_s(p , j)
        addval = (pref[j][x] - pref[j][ind]) - (x * (x - 1)) // 2
        ans = min(ans , solve(mask | (1 << j)) + addval)

    dp[mask] = ans
    return ans

def answer():

    global dp , pos , pref

    pref = [[0] for j in range(20)]
    pos = [[] for i in range(20)]
    for i in range(n):
        pos[a[i]].append(i)
        pref[a[i]].append(pref[a[i]][-1] + i)

    dp = [-1 for i in range(1 << 20)]

    ans = solve(0)
    return ans

for T in range(1):

    n = int(input())
    a = inp()

    for i in range(n):
        a[i] -= 1

    print(answer())

Monocarp has arranged $$$n$$$ colored marbles in a row. The color of the $$$i$$$-th marble is $$$a_i$$$. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color). In other words, Monocarp wants to rearrange marbles so that, for every color $$$j$$$, if the leftmost marble of color $$$j$$$ is $$$l$$$-th in the row, and the rightmost marble of this color has position $$$r$$$ in the row, then every marble from $$$l$$$ to $$$r$$$ has color $$$j$$$.To achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them.You have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.

The first line contains one integer $$$n$$$ $$$(2 \le n \le 4 \cdot 10^5)$$$ — the number of marbles.
The second line contains an integer sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 20)$$$, where $$$a_i$$$ is the color of the $$$i$$$-th marble.

Print the minimum number of operations Monocarp has to perform to achieve his goal.

from sys import stdin
input = stdin.readline

inp = lambda : list(map(int,input().split()))

N = 20

def solve(mask):

    if(mask == (1 << N) - 1):return 0
    if(dp[mask] != -1):return dp[mask]

    p = 0
    for i in range(N):
        if(mask >> i & 1):
            p += count[i]

    ans = float('inf')
    for i in range(N):
        if(mask >> i & 1):continue

        addval = total[i]
        for j in range(N):
            if(mask >> j & 1 == 0 and i != j):continue
            addval -= val[i][j]

        ans = min(ans , solve(mask | (1 << i)) + addval)

    dp[mask] = ans
    return ans

def answer():

    global dp , val , total , count

    total = [0 for i in range(N)]
    val = [[0 for i in range(N)] for j in range(N)]
    count = [0 for i in range(N)]
    for i in range(n):

        for j in range(N):
            val[a[i]][j] += count[j]

        total[a[i]] += i
        count[a[i]] += 1

    dp = [-1 for i in range(1 << N)]

    ans = solve(0)
    return ans

for T in range(1):

    n = int(input())
    a = inp()

    for i in range(n):
        a[i] -= 1

    print(answer())


import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

N = 10**5
s = []
for i in range(1, N):
    s += list(str(i))

q = int(input())

for _ in range(q):
    k = int(input())
    k -= 1
    l = 0
    for i in range(1, N):
        k -= l
        l += len(str(i))
        if 0 <= k <= l:
            print(s[k])
            break

The only difference between the easy and the hard versions is the maximum value of $$$k$$$.You are given an infinite sequence of form "112123123412345$$$\dots$$$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $$$1$$$ to $$$1$$$, the second one — from $$$1$$$ to $$$2$$$, the third one — from $$$1$$$ to $$$3$$$, $$$\dots$$$, the $$$i$$$-th block consists of all numbers from $$$1$$$ to $$$i$$$. So the first $$$56$$$ elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the $$$1$$$-st element of the sequence is $$$1$$$, the $$$3$$$-rd element of the sequence is $$$2$$$, the $$$20$$$-th element of the sequence is $$$5$$$, the $$$38$$$-th element is $$$2$$$, the $$$56$$$-th element of the sequence is $$$0$$$.Your task is to answer $$$q$$$ independent queries. In the $$$i$$$-th query you are given one integer $$$k_i$$$. Calculate the digit at the position $$$k_i$$$ of the sequence.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries.
The $$$i$$$-th of the following $$$q$$$ lines contains one integer $$$k_i$$$ $$$(1 \le k_i \le 10^9)$$$ — the description of the corresponding query.

Print $$$q$$$ lines. In the $$$i$$$-th line print one digit $$$x_i$$$ $$$(0 \le x_i \le 9)$$$ — the answer to the query $$$i$$$, i.e. $$$x_i$$$ should be equal to the element at the position $$$k_i$$$ of the sequence.

import sys
from collections import deque
input = sys.stdin.readline
def fgh():
    return [int(xx) for xx in input().split()]
def fg():
    return int(input())
step = [1]
for i in range(22):
    step.append(step[-1] * 10)
def f(n):
    ans = 0
    for i in range(20):
        ans += max(0, n - step[i] + 1)
    return ans
def g(n):
    ans = 0
    for i in range(20):
        q = max(0, n - step[i] + 1)
        ans += q * (q + 1) // 2 + q * max(0, n - (step[i] + q))
    return ans
for __ in range(fg()):
    n = fg()
    l = 0
    r = 10 ** 19
    while r - l > 1:
        m = (l + r) // 2
        if g(m) < n:
            l = m
        else:
            r = m
    n -= g(l)
    r = l + 1
    l = 0
    while r - l > 1:
        m = (l + r) // 2
        if f(m) < n:
            l = m
        else:
            r = m
    n -= f(l)
    print(str(l + 1)[n - 1])


The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries.
The $$$i$$$-th of the following $$$q$$$ lines contains one integer $$$k_i$$$ $$$(1 \le k_i \le 10^{18})$$$ — the description of the corresponding query.

from math import *

def quick_pow(n, p):
    ret = 1
    while p:
        if p & 1:
            ret *= n
        n *= n
        p >>= 1
    return ret

def len(n):
    cnt = 0
    while n:
        cnt += 1
        n = int(n/10)
    return cnt

sum = [0, 45, 9045, 1395495, 189414495, 23939649495, 2893942449495,
       339393974949495, 38939394344949495, 4393939398494949495]
pre = [0, 9, 189, 2889, 38889, 488889,
       5888889, 68888889, 788888889, 8888888889]
# int q, l
# llk, start, cnt, finish_int, i, left, right, mid, a, b, c
q = int(input())
for a in range(q):
    k = int(input())
    # l = upper_bound(sum, sum + 10, k) - sum
    for l in range(11):
        if sum[l] >= k:
            break
    k -= sum[l - 1]
    start = pre[l - 1] + l
    # // left = 0, right = quick_pow(10, l) - quick_pow(10, l - 1) - 1
    # // while (left < right) {
    #     // mid = (left + right) >> 1
    #     // if ((start + start + l * (mid - 1)) * mid / 2 < k)
    #     // left = mid + 1
    #     // else
    #     // right = mid - 1
    #     // }
    # // if ((start + start + l * (right - 1)) * right / 2 > k)
    # // --right
    a = l
    b = 2 * start + l
    c = 2 * start - 2 * k
    cnt = int(ceil((-b + sqrt(b * b - 4 * a * c)) / (2 * a)))
    # print(int((start + start + (cnt - 1) * l) * cnt))
    # print(int(int((start + start + (cnt - 1) * l) * cnt)//2))
    k -= ((start + start + (cnt - 1) * l) * cnt // 2)
    # // if (right > 1)
    # // k -= pre[len(right) - 1] + len(right - 1) * (right - 1 - quick_pow(10, len(right) - 1) + 1)
    finish_int = quick_pow(10, l - 1) + cnt
    left = 1
    right = finish_int
    while left < right:
        mid = (left + right) >> 1
        t = len(mid)
        if pre[t - 1] + len(mid) * (mid - quick_pow(10, t - 1) + 1) < k:
            left = mid + 1
        else:
            right = mid
    t = len(right)
    if right > 1:
        k -= pre[t - 1] + len(right - 1) * (right - quick_pow(10, t - 1))
    # stringstream ss
    # string str
    # ss << left
    # ss >> str
    # cout << str[k - 1] << endl
    right = str(right)
    print(right[k-1])