parseline(str=readline()) = parse.(Int, split(str))
function StringFormation()
    S = readline()
    Q = parseline()
    queries = split.(readlines())
    inverse = false
    ans = [S]
    for q in queries
        l = length(q)
        l≡0 && continue
        if l≡1
            inverse = !inverse
        else
            head = q[2]=="1" ? true : false
            head = inverse ? !head : head
            head ? pushfirst!(ans, q[3]) : push!(ans, q[3])
        end
    end
    ret = prod(ans)
    println(inverse ? ret[end:-1:1] : ret)
end
StringFormation()

Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

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

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy


parseline(str=readline()) = parse.(Int, split(str))
function StringFormation()
    S = readline()
    Q = parseline()
    queries = split.(readlines())
    inverse = false
    ans = [s]
    for q in queries
        l = length(q)
        l≡0 && continue
        if l≡1
            inverse = !inverse
        else
            head = q[2]=="1" ? true : false
            head = inverse ? !head : head
            head ? pushfirst!(S, q[3]) : push!(S, q[3])
        end
    end
    println(prod(inverse ? ans[end:-1:1] : ans))
end
StringFormation()

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

Submitted source-code file size, in bytes.

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

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


n = parse(Int64, readline())
println(div(n + 1, 2))

Score : 100 points

Problem Statement

Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.

At least how many sheets of paper does he need?

Constraints

N is an integer.

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

5

Sample Output 1

3

By printing the 1-st, 2-nd pages on the 1-st sheet, 3-rd and 4-th pages on the 2-nd sheet, and 5-th page on the 3-rd sheet, we can print all the data on 3 sheets of paper.

Sample Input 2

2

Sample Output 2

1

Sample Input 3

100

Sample Output 3

50


A=Int[]
for _=1:3
	for a=parse.(split(readline()))
		push!(A,a)
	end
end
ok=zeros(Int,9)
for _=1:parse(readline())
	b=parse(readline())
	for i=1:9
		if A[i]==b
			ok[i]=1
		end
	end
end
println(ok[1]*ok[2]*ok[3]+ok[4]*ok[5]*ok[6]+ok[7]*ok[8]*ok[9]+ok[1]*ok[4]*ok[7]+ok[2]*ok[5]*ok[8]+ok[3]*ok[6]*ok[9]+ok[1]*ok[5]*ok[9]+ok[3]*ok[5]*ok[7]>0 ? "Yes" : "No")

Score : 200 points

Problem Statement

We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.

The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.

Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

Constraints

All values in input are integers.

1 \leq A_{i, j} \leq 100

A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))

1 \leq N \leq 10

1 \leq b_i \leq 100

b_i \neq b_j (i \neq j)

Input

Input is given from Standard Input in the following format:

A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N

Output

If we will have a bingo, print Yes; otherwise, print No.

Sample Input 1

84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

Sample Output 1

Yes

We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.

Sample Input 2

41 7 46
26 89 2
78 92 8
5
6
45
16
57
17

Sample Output 2

No

We will mark nothing.

Sample Input 3

60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34

Sample Output 3

Yes

We will mark all the squares.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	a = zeros(Int,3,3)
	for i in 1:3
		a[i,:] = readline() |> split |> parseMap
	end
	chk = zeros(Int,3,3)
	f = 0
	n = readline() |> parseInt
	for i in 1:n
		b = readline() |> parseInt
		for i in 1:3
			for j in 1:3
				if a[i,j] == b
					chk[i,j] = 1
				end
			end
		end
	end
	for i in 1:3
		if sum(chk[i,:])==3
			f = 1
		end
		if sum(chk[:,i])==3
			f = 1
		end
	end
	if chk[1,1]+chk[2,2]+chk[3,3]==3
		f = 1
	end
	if chk[3,1]+chk[2,2]+chk[1,3]==3
		f = 1
	end
	println(f==1?"Yes":"No")
end

main()


N,M,K=map(x->parse(Int64,x),split(readline()))

Yuko=zeros(Bool,N,N)
Block=zeros(Bool,N,N)

for i in 1:M
    A,B=map(x->parse(Int64,x),split(readline()))
    Yuko[A,B]=true
    Yuko[B,A]=true
end
for i in 1:K
    A,B=map(x->parse(Int64,x),split(readline()))
    Block[A,B]=true
    Block[B,A]=true
end
a2a(V1,V2)=    [(V1[i] || V2[i])  for i in 1:length(V1)]
Tomo=copy(Yuko)
for i in 1:N
    tmp=copy(Tomo[i,:])
    flag=true
    while flag
        for j in 1:N
            if Tomo[i,j]==true
                #println("add",i,",",j)
                #Tomo[i,:]+=Tomo[j,:]
                Tomo[i,:]=a2a(Tomo[i,:],Tomo[j,:])
            end
        end
        if tmp == Tomo[i,:]
            flag=false
        end
        tmp=copy(Tomo[i,:])
    end
end

cTomo=zeros(Int,N)
for i in 1:N ,j in 1:N
    if (Tomo[i,j] && (!Yuko[i,j] && !Block[i,j]))
        i!=j && (cTomo[i]+=1)
    end
end

print(cTomo[1])
for i in 2:N
    print(" ",cTomo[i])
end

Score : 400 points

Problem Statement

An SNS has N users - User 1, User 2, \cdots, User N.

Between these N users, there are some relationships - M friendships and K blockships.

For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.

For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i and User D_i.

We define User a to be a friend candidate for User b when all of the following four conditions are satisfied:

a \neq b.

There is not a friendship between User a and User b.

There is not a blockship between User a and User b.

There exists a sequence c_0, c_1, c_2, \cdots, c_L consisting of integers between 1 and N (inclusive) such that c_0 = a, c_L = b, and there is a friendship between User c_i and c_{i+1} for each i = 0, 1, \cdots, L - 1.

For each user i = 1, 2, ... N, how many friend candidates does it have?

Constraints

All values in input are integers.

2 ≤ N ≤ 10^5

0 \leq M \leq 10^5

0 \leq K \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

1 \leq C_i, D_i \leq N

C_i \neq D_i

(A_i, B_i) \neq (A_j, B_j) (i \neq j)

(A_i, B_i) \neq (B_j, A_j)

(C_i, D_i) \neq (C_j, D_j) (i \neq j)

(C_i, D_i) \neq (D_j, C_j)

(A_i, B_i) \neq (C_j, D_j)

(A_i, B_i) \neq (D_j, C_j)

Input

Input is given from Standard Input in the following format:

N M K
A_1 B_1
\vdots
A_M B_M
C_1 D_1
\vdots
C_K D_K

Output

Print the answers in order, with space in between.

Sample Input 1

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

Sample Output 1

0 1 0 1

There is a friendship between User 2 and 3, and between 3 and 4. Also, there is no friendship or blockship between User 2 and 4. Thus, User 4 is a friend candidate for User 2.

However, neither User 1 or 3 is a friend candidate for User 2, so User 2 has one friend candidate.

Sample Input 2

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

Sample Output 2

0 0 0 0 0

Everyone is a friend of everyone else and has no friend candidate.

Sample Input 3

10 9 3
10 1
6 7
8 2
2 5
8 4
7 3
10 9
6 4
5 8
2 6
7 5
3 1

Sample Output 3

1 3 5 4 3 3 3 3 1 0


type UF
	n::Int
	pr::Array{Int}
	sz::Array{Int}
	UF(n)=new(n,1:n,ones(Int,n))
end
function find(uf::UF,a::Int)
	if uf.pr[a]==a
		a
	else
		uf.pr[a]=find(uf,uf.pr[a])
	end
end
same(uf::UF,a::Int,b::Int)=find(uf,a)==find(uf,b)
function unite(uf::UF,a::Int,b::Int)
	ap=find(uf,a)
	bp=find(uf,b)
	if ap==bp
		false
	else
		if uf.sz[ap]<uf.sz[bp]
			uf.pr[ap]=bp
			uf.sz[bp]+=uf.sz[ap]
		else
			uf.pr[bp]=ap
			uf.sz[ap]+=uf.sz[bp]
		end
		true
	end
end
size(uf::UF,a::Int)=uf.sz[find(uf,a)]
function main()
	N,M,K=map(x->parse(Int,x),split(readline()))
	uf=UF(N)
	G=[Int[] for _=1:N]
	for _=1:M
		a,b=map(x->parse(Int,x),split(readline()))
		push!(G[a],b)
		push!(G[b],a)
		unite(uf,a,b)
	end
	for _=1:K
		a,b=map(x->parse(Int,x),split(readline()))
		push!(G[a],b)
		push!(G[b],a)
	end
	for i=1:N
		ans=size(uf,i)
		for v=G[i]
			if same(uf,i,v)
				ans-=1
			end
		end
		println(ans-1)
	end
end
main()


const N,K=map(x->parse(Int,x),split(readline()))
const X=Float64[]
const Y=Float64[]
const C=Float64[]
for _=1:N
	x,y,c=map(x->parse(Float64,x),split(readline()))
	push!(X,x)
	push!(Y,y)
	push!(C,c)
end
function check(M)
	A=Pair{Float64,Float64}[]
	for i=1:N
		push!(A,X[i]=>Y[i])
	end
	r=[M/c for c=C]
	for i=1:N,j=i+1:N
		d=sqrt((X[i]-X[j])^2+(Y[i]-Y[j])^2)
		ri=r[i]
		rj=r[j]
		if d<abs(ri-rj)||ri+rj<d
			continue
		end
		a=acos((ri^2+d^2-rj^2)/(2*ri*d))
		t=atan(Y[j]-Y[i],X[j]-X[i])
		push!(A,X[i]+ri*cos(t+a)=>Y[i]+ri*sin(t+a))
		push!(A,X[i]+ri*cos(t-a)=>Y[i]+ri*sin(t-a))
	end
	ret=false;
	for (x,y)=A
		cnt=0
		for i=1:N
			if sqrt((X[i]-x)^2+(Y[i]-y)^2)<=r[i]+1e-10
				cnt+=1
			end
		end
		if cnt>=K
			ret=true
		end
	end
	ret
end
function main()
	L=0
	R=1e9
	for _=1:100
		M=(L+R)/2
		if check(M)
			R=M
		else
			L=M
		end
	end
	println(R)
end
main()

Score : 600 points

Problem Statement

Takahashi wants to grill N pieces of meat on a grilling net, which can be seen as a two-dimensional plane. The coordinates of the i-th piece of meat are \left(x_i, y_i\right), and its hardness is c_i.

Takahashi can use one heat source to grill the meat. If he puts the heat source at coordinates \left(X, Y\right), where X and Y are real numbers, the i-th piece of meat will be ready to eat in c_i \times \sqrt{\left(X - x_i\right)^2 + \left(Y-y_i\right)^2} seconds.

Takahashi wants to eat K pieces of meat. Find the time required to have K or more pieces of meat ready if he put the heat source to minimize this time.

Constraints

All values in input are integers.

1 \leq N \leq 60

1 \leq K \leq N

-1000 \leq x_i , y_i \leq 1000

\left(x_i, y_i\right) \neq \left(x_j, y_j\right) \left(i \neq j \right)

1 \leq c_i \leq 100

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1 c_1
\vdots
x_N y_N c_N

Output

Print the answer.

It will be considered correct if its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

4 3
-1 0 3
0 0 3
1 0 2
1 1 40

Sample Output 1

2.4

If we put the heat source at \left(-0.2, 0\right), the 1-st, 2-nd, and 3-rd pieces of meat will be ready to eat within 2.4 seconds. This is the optimal place to put the heat source.

Sample Input 2

10 5
-879 981 26
890 -406 81
512 859 97
362 -955 25
128 553 17
-885 763 2
449 310 57
-656 -204 11
-270 76 40
184 170 16

Sample Output 2

7411.2252


Score : 100 points

Problem Statement

Takahashi is a member of a programming competition site, ButCoder.

Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.

The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus 100 \times (10 - K) when the member has participated in K contests.

Takahashi has participated in N contests, and his Displayed Rating is R. Find his Inner Rating.

Constraints

All values in input are integers.

1 \leq N \leq 100

0 \leq R \leq 4111

Input

Input is given from Standard Input in the following format:

N R

Output

Print his Inner Rating.

Sample Input 1

2 2919

Sample Output 1

3719

Takahashi has participated in 2 contests, which is less than 10, so his Displayed Rating is his Inner Rating minus 100 \times (10 - 2) = 800.

Thus, Takahashi's Inner Rating is 2919 + 800 = 3719.

Sample Input 2

22 3051

Sample Output 2

3051


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n,r=parseMap(split(readline()))
    println(ifelse(n>=10,r,r+100*(10-n)))
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n,k=parseMap(split(readline()))
    println(ndigits(n,k))
end
main()

Score : 200 points

Problem Statement

Given is an integer N. Find the number of digits that N has in base K.

Notes

For information on base-K representation, see Positional notation - Wikipedia.

Constraints

All values in input are integers.

1 \leq N \leq 10^9

2 \leq K \leq 10

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of digits that N has in base K.

Sample Input 1

11 2

Sample Output 1

4

In binary, 11 is represented as 1011.

Sample Input 2

1010101 10

Sample Output 2

7

Sample Input 3

314159265 3

Sample Output 3

18


function main()

  (N,K) = map(x -> parse(Int,x), split(readline()))

  println(floor(Int,log(K,N))+1)

end

main()


parseInt(x) = parse(Int, x)
n,k = parseInt.(split(readline()))
num = 1
cnt = 0
while num <= n
    global num *= k
    global cnt+=1
println(cnt)


parseInt(x) = parse(Int, x)
n,k = parseInt.(split(readline()))
println(length(string(n, base = k)))


function K_kuri(N,P,M)
    ( P ≤ 0 )  && return 1
    ( P%2==0 ) && return K_kuri(N,P÷2,M)^2 % M
    N*K_kuri(N,P-1,M) % M
end

function CmbMod(a,b,M)
    A=B=1
    for i in 1:b
        A*=(a-i+1)%M
        B*=K_kuri(i,M-2,M)
        A%=M
        B%=M
    end
    A*B%M
end

input=split(readline())
MOD=10^9+7
N,a,b=map(x->parse(Int,x),input)

print((K_kuri(2,N,MOD)-1-CmbMod(N,a,MOD)-CmbMod(N,b,MOD)+3MOD)%MOD)

Score : 400 points

Problem Statement

Akari has n kinds of flowers, one of each kind.

She is going to choose one or more of these flowers to make a bouquet.

However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.

How many different bouquets are there that Akari can make?

Find the count modulo (10^9 + 7).

Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet.

Constraints

All values in input are integers.

2 \leq n \leq 10^9

1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5)

Input

Input is given from Standard Input in the following format:

n a b

Output

Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print 0.)

Sample Input 1

4 1 3

Sample Output 1

7

In this case, Akari can choose 2 or 4 flowers to make the bouquet.

There are 6 ways to choose 2 out of the 4 flowers, and 1 way to choose 4, so there are a total of 7 different bouquets that Akari can make.

Sample Input 2

1000000000 141421 173205

Sample Output 2

34076506

Print the count modulo (10^9 + 7).


parseInt(x) = parse(Int, x);
parseMap(x::Array{SubString{String},1}) = map(parseInt, x);

N_MAX = 2 * 10^5;
fac = Array{Int}(N_MAX+1);
inv = Array{Int}(N_MAX+1);
MOD = 10^9 + 7;
#初期化
function COMINIT();fac[1] = 1;for i in 1:N_MAX-1;fac[i+1] = fac[i] * (i+1) % MOD;end;for i in 1:N_MAX;inv[i] = powermod(fac[i], MOD-2, MOD);end;end;
#nCk
function Comb(n, k);if n <= 0 || k < 0;return 0;end;if k > n;return 0;end;if k == 0 || n == k;return 1;end;return ((fac[n] * inv[k]) % MOD * inv[n-k])%MOD;end;
function H(n, m);return Comb(n + m, m);end;
function main();COMINIT();n,k = parseInt.(split(readline()));m = min(k, n-1);ans = 0;for i in 0:m;ans += (Comb(n,i) * H(n-1-i,i)) % MOD;ans %= MOD;end;println(ans);end;
main();

Score : 500 points

Problem Statement

There is a building with n rooms, numbered 1 to n.

We can move from any room to any other room in the building.

Let us call the following event a move: a person in some room i goes to another room j~ (i \neq j).

Initially, there was one person in each room in the building.

After that, we know that there were exactly k moves happened up to now.

We are interested in the number of people in each of the n rooms now. How many combinations of numbers of people in the n rooms are possible?

Find the count modulo (10^9 + 7).

Constraints

All values in input are integers.

3 \leq n \leq 2 \times 10^5

2 \leq k \leq 10^9

Input

Input is given from Standard Input in the following format:

n k

Output

Print the number of possible combinations of numbers of people in the n rooms now, modulo (10^9 + 7).

Sample Input 1

3 2

Sample Output 1

10

Let c_1, c_2, and c_3 be the number of people in Room 1, 2, and 3 now, respectively. There are 10 possible combination of (c_1, c_2, c_3):

(0, 0, 3)

(0, 1, 2)

(0, 2, 1)

(0, 3, 0)

(1, 0, 2)

(1, 1, 1)

(1, 2, 0)

(2, 0, 1)

(2, 1, 0)

(3, 0, 0)

For example, (c_1, c_2, c_3) will be (0, 1, 2) if the person in Room 1 goes to Room 2 and then one of the persons in Room 2 goes to Room 3.

Sample Input 2

200000 1000000000

Sample Output 2

607923868

Print the count modulo (10^9 + 7).

Sample Input 3

15 6

Sample Output 3

22583772


const lines=readlines()
const k,q=map(x->parse(Int,x),split(shift!(lines)))
const d=map(x->parse(Int,x),split(shift!(lines)))
for t=lines
  const n,x,m=map(x->parse(Int,x),split(t))
  s=Int[0]
  pre=0
  for i=1:k
    pre+=mod1(d[i],m)
    push!(s,pre)
  end
  println(n-1-div(x%m+div(n-1,k)*pre+s[mod1(n,k)],m))
end

Score : 600 points

Problem Statement

We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.

Process the following q queries in order:

The i-th query contains three integers n_i, x_i, and m_i.
Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray}
Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).

Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).

Constraints

All values in input are integers.

1 \leq k, q \leq 5000

0 \leq d_i \leq 10^9

2 \leq n_i \leq 10^9

0 \leq x_i \leq 10^9

2 \leq m_i \leq 10^9

Input

Input is given from Standard Input in the following format:

k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q

Output

Print q lines.

The i-th line should contain the response to the i-th query.

Sample Input 1

3 1
3 1 4
5 3 2

Sample Output 1

1

For the first query, the sequence {a_j} will be 3,6,7,11,14.

(a_0~\textrm{mod}~2) > (a_1~\textrm{mod}~2)

(a_1~\textrm{mod}~2) < (a_2~\textrm{mod}~2)

(a_2~\textrm{mod}~2) = (a_3~\textrm{mod}~2)

(a_3~\textrm{mod}~2) > (a_4~\textrm{mod}~2)

Thus, the response to this query should be 1.

Sample Input 2

7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12

Sample Output 2

224489796
214285714
559523809


const lines=readlines()
const k,q=map(x->parse(Int,x),split(shift!(lines)))
const d=map(x->parse(Int,x),split(shift!(lines)))
for s=lines
  n,x,m=map(x->parse(Int,x),split(s))
  b=x%m
  for i=1:k
    b+=mod1(d[i],m)*div(n-i-1+k,k)
  end
  println(n-1-div(b,m))
end


A,B,C=split(chomp(readline())," ")
if (A==B && A!=C) || (A==C && B!=C) || (B==C && A!=C)
  print("Yes")
else
  print("No")
end

Score: 100 points

Problem Statement

A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers.

You will be given three integers A, B, and C. If this triple is poor, print Yes; otherwise, print No.

Constraints

A, B, and C are all integers between 1 and 9 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C

Output

If the given triple is poor, print Yes; otherwise, print No.

Sample Input 1

5 7 5

Sample Output 1

Yes

A and C are equal, but B is different from those two numbers, so this triple is poor.

Sample Input 2

4 4 4

Sample Output 2

No

A, B, and C are all equal, so this triple is not poor.

Sample Input 3

4 9 6

Sample Output 3

No

Sample Input 4

3 3 4

Sample Output 4

Yes


S = Set(split(readline()))
if length(S) == 2
    println("Yes")
else
    println("No")
end


#!/usr/bin/env -S JULIA_VERSION=0.5.0 julia
# contest: abc155, problem: abc155_c, alphabet: C

function solve(N::Int, S::Vector{String})
  c = Dict{String, Int}()
  for s in S
    c[s] = get(c, s, 0) + 1
  end
  maxc = maximum(last, c)
  for s in sort(collect(filter(x->last(x) == maxc, c)))
    println(first(s))
  end
end

function main()
  tokens = Channel{String}(32)
  Task() do
    for line in eachline(@static VERSION < v"0.6" ? STDIN : stdin)
      startswith(line, '\0') && break
      for token in split(chomp(line))
        put!(tokens, token)
      end
    end
    close(tokens)
  end |> schedule
  N = parse(Int, take!(tokens))
  S = similar(Vector{String}, N)
  for i in 1:N
    S[i] = take!(tokens)
  end
  solve(N, S)
end

if isempty(get(ENV, "ATCODER_LOCAL", ""))
  isempty(ARGS) && main()
else
  @eval begin
    const samples = [("7\nbeat\nvet\nbeet\nbed\nvet\nbet\nbeet", "beet\nvet"), ("8\nbuffalo\nbuffalo\nbuffalo\nbuffalo\nbuffalo\nbuffalo\nbuffalo\nbuffalo", "buffalo"), ("7\nbass\nbass\nkick\nkick\nbass\nkick\nkick", "kick"), ("4\nushi\ntapu\nnichia\nkun", "kun\nnichia\ntapu\nushi")]
    function test(sampleids...)
      isempty(sampleids) && return test(collect(1:length(samples))...)
      ostdin, ostdout = @static VERSION < v"0.6" ? (STDIN, STDOUT) : (stdin, stdout)
      rd, wr = first(redirect_stdout()), last(redirect_stdin())
      try
        map(sampleids) do sampleid
          input, output = samples[sampleid]
          print(ostdout, "Testing sample #$(sampleid)..."); flush(ostdout)
          println(wr, input)
          println(wr, "\0")
          t = @elapsed main()
          println()
          result = strip(String(readavailable(rd)))
          if result == output
            println(ostdout, "OK ($t sec).")
            true
          else
            println(ostdout, "ERROR ($t sec)")
            println(ostdout, "== expected ==\n$output")
            println(ostdout, "== actual ==\n$result\n")
            false
          end
        end |> all
      finally
        redirect_stdin(ostdin)
        redirect_stdout(ostdout)
      end
    end
    submit() = test() && (prog = @__FILE__; run(`atcoder-submit $prog`))
    !isinteractive() && submit()
  end
end

Score: 300 points

Problem Statement

We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it.

Print all strings that are written on the most number of votes, in lexicographical order.

Constraints

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

S_i (1 \leq i \leq N) are strings consisting of lowercase English letters.

The length of S_i (1 \leq i \leq N) is between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print all strings in question in lexicographical order.

Sample Input 1

7
beat
vet
beet
bed
vet
bet
beet

Sample Output 1

beet
vet

beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet.

Sample Input 2

8
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo

Sample Output 2

buffalo

Sample Input 3

7
bass
bass
kick
kick
bass
kick
kick

Sample Output 3

kick

Sample Input 4

4
ushi
tapu
nichia
kun

Sample Output 4

kun
nichia
tapu
ushi


function main()

  N = parse(Int,readline())

  S = String[]
  S_0 = String[]

  for i in 1:N

    push!(S,chomp(readline()))

    if in(S[i],S_0) == false
      push!(S_0,S[i])
    end

  end

  sort!(S_0)

  num_max = 0

  dict = Dict{String,Int64}()

  for i in 1:N

    if haskey(dict,S[i])
      dict[S[i]] += 1
    else
      dict[S[i]] = 1
    end

  end

  num_max = maximum(values(dict))

  for i in 1:length(S_0)

    if dict[S_0[i]] == num_max
      println(S_0[i])
    end

  end

end

main()


s,t=split(readline())
x,y=parse.(split(readline()))
u=chomp(readline())
if s==u
  x-=1
else
  y-=1
end
println("$x $y")

Score : 100 points

Problem Statement

We have A balls with the string S written on each of them and B balls with the string T written on each of them.

From these balls, Takahashi chooses one with the string U written on it and throws it away.

Find the number of balls with the string S and balls with the string T that we have now.

Constraints

S, T, and U are strings consisting of lowercase English letters.

The lengths of S and T are each between 1 and 10 (inclusive).

S \not= T

S=U or T=U.

1 \leq A,B \leq 10

A and B are integers.

Input

Input is given from Standard Input in the following format:

S T
A B
U

Output

Print the answer, with space in between.

Sample Input 1

red blue
3 4
red

Sample Output 1

2 4

Takahashi chose a ball with red written on it and threw it away.
Now we have two balls with the string S and four balls with the string T.

Sample Input 2

red blue
5 5
blue

Sample Output 2

5 4

Takahashi chose a ball with blue written on it and threw it away.
Now we have five balls with the string S and four balls with the string T.


Score : 200 points

Problem Statement

Given is a string S. Replace every character in S with x and print the result.

Constraints

S is a string consisting of lowercase English letters.

The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Replace every character in S with x and print the result.

Sample Input 1

sardine

Sample Output 1

xxxxxxx

Replacing every character in S with x results in xxxxxxx.

Sample Input 2

xxxx

Sample Output 2

xxxx

Sample Input 3

gone

Sample Output 3

xxxx


S = chomp(readline())
len = length(S)
print("x"^len)


n=parse(Int,readline())
println(n>length(unique(sort(map(x->parse(Int,x),split(readline()))))) ? "NO" : "YES")

Score : 300 points

Problem Statement

Given is a sequence of integers A_1, A_2, ..., A_N.
If its elements are pairwise distinct, print YES; otherwise, print NO.

Constraints

2 ≤ N ≤ 200000

1 ≤ A_i ≤ 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

If the elements of the sequence are pairwise distinct, print YES; otherwise, print NO.

Sample Input 1

5
2 6 1 4 5

Sample Output 1

YES

The elements are pairwise distinct.

Sample Input 2

6
4 1 3 1 6 2

Sample Output 2

NO

The second and fourth elements are identical.

Sample Input 3

2
10000000 10000000

Sample Output 3

NO


function main()

  (N, K) = map(x -> parse(Int,x), split(readline()))
  P = map(x -> parse(Int,x), split(readline()))

  exp = []

  for n in P
    push!(exp, (n+1)/2)
  end

  ans = 0

  for i in 1:N-K+1
    ans = max(ans, sum(exp[i:i+K-1]))
  end

  println(ans)

end

main()

Score : 400 points

Problem Statement

We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown.

We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this sum.

Constraints

1 ≤ K ≤ N ≤ 200000

1 ≤ p_i ≤ 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 ... p_N

Output

Print the maximum possible value of the expected value of the sum of the numbers shown.

Your output will be considered correct when its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

5 3
1 2 2 4 5

Sample Output 1

7.000000000000

When we throw the third, fourth, and fifth dice from the left, the expected value of the sum of the numbers shown is 7. This is the maximum value we can achieve.

Sample Input 2

4 1
6 6 6 6

Sample Output 2

3.500000000000

Regardless of which die we choose, the expected value of the number shown is 3.5.

Sample Input 3

10 4
17 13 13 12 15 20 10 13 17 11

Sample Output 3

32.000000000000


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n,k=parseMap(split(readline()))
    p=parseMap(split(readline()))
    res=sum(Vector(p[1:k]))
    m=res
    for i in k+1:n
        res+=p[i]-p[i-k]
        m=max(res,m)
    end
    println((k+m)/2)
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	a = parseMap(split(chomp(readline()),""))
	k = readline() |> parseInt
	n = length(a)
	dp = zeros(Int,n,k+1,2)
	dp[1,2,1] = a[1]-1
	dp[1,2,2] = 1
	dp[1,1,1] = 1
	for i in 2:n
		for j in 1:k+1
			dp[i,j,1] += dp[i-1,j,1]+dp[i-1,j,2]
			if a[i] == 0
				dp[i,j,2] = dp[i-1,j,2]
			else
				dp[i,j,2] = 0
			end
			if j>1
				dp[i,j,1] += dp[i-1,j-1,1]*9+dp[i-1,j-1,2]*(max(a[i]-1,0))
				if a[i]>0
					dp[i,j,2] = dp[i-1,j-1,2]
				else
					dp[i,j,2] = 0
				end
			end
		end
	end
	println(dp[n,k+1,1]+dp[n,k+1,2])
end

main()

Score : 500 points

Problem Statement

Find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten.

Constraints

1 \leq N < 10^{100}

1 \leq K \leq 3

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the count.

Sample Input 1

100
1

Sample Output 1

19

The following 19 integers satisfy the condition:

1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100

Sample Input 2

25
2

Sample Output 2

14

The following 14 integers satisfy the condition:

11,12,13,14,15,16,17,18,19,21,22,23,24,25

Sample Input 3

314159
2

Sample Output 3

937

Sample Input 4

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
3

Sample Output 4

117879300


function main()
  a,b = parse.(split(readline()))
  if a<=sum(parse.(split(readline())))
    println("Yes")
  else
    println("No")
  end
end

main()

Score : 200 points

Problem Statement

Raccoon is fighting with a monster.

The health of the monster is H.

Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i.
There is no other way to decrease the monster's health.

Raccoon wins when the monster's health becomes 0 or below.

If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

Constraints

1 \leq H \leq 10^9

1 \leq N \leq 10^5

1 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H N
A_1 A_2 ... A_N

Output

If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

Sample Input 1

10 3
4 5 6

Sample Output 1

Yes

The monster's health will become 0 or below after, for example, using the second and third moves.

Sample Input 2

20 3
4 5 6

Sample Output 2

No

Sample Input 3

210 5
31 41 59 26 53

Sample Output 3

Yes

Sample Input 4

211 5
31 41 59 26 53

Sample Output 4

No


function main()

  (N,K) = map(x -> parse(Int,x), split(readline()))

  H = map(x -> parse(Int,x), split(readline()))
  sort!(H,rev = true)

  ans = 0

  for i in K+1:N

    ans += H[i]

  end

  println(ans)

end

main()

Score : 300 points

Problem Statement

Fennec is fighting with N monsters.

The health of the i-th monster is H_i.

Fennec can do the following two actions:

Attack: Fennec chooses one monster. That monster's health will decrease by 1.

Special Move: Fennec chooses one monster. That monster's health will become 0.

There is no way other than Attack and Special Move to decrease the monsters' health.

Fennec wins when all the monsters' healths become 0 or below.

Find the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning when she can use Special Move at most K times.

Constraints

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

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

1 \leq H_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
H_1 ... H_N

Output

Print the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning.

Sample Input 1

3 1
4 1 5

Sample Output 1

5

By using Special Move on the third monster, and doing Attack four times on the first monster and once on the second monster, Fennec can win with five Attacks.

Sample Input 2

8 9
7 9 3 2 3 8 4 6

Sample Output 2

0

She can use Special Move on all the monsters.

Sample Input 3

3 0
1000000000 1000000000 1000000000

Sample Output 3

3000000000

Watch out for overflow.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function bsearch(a,x);l,r=0,length(a)+1;while r-l>1;m=(r+l)>>1;if a[m]<=x;l=m;else;r=m;end;end;l;end
function bsearchg(a,x);l,r=0,length(a)+1;while r-l>1;m=(r+l)>>1;if a[m]<x;l=m;else;r=m;end;end;l;end
function main()
	n,d,a = readline() |> split |> parseMap
	b = Tuple{Int,Int}[(0,0) for i in 1:n]
	for i in 1:n
		p,q = readline() |> split |> parseMap
		b[i]=(p,q)
	end
	b = sort(b,by=x->x[1])
	x = [b[i][1] for i in 1:n]
	h = [b[i][2] for i in 1:n]
	lm = Int[0]
	v = Int[0]
	s = 0
	m = 1
	for i in 1:n
		r = bsearch(x,x[i]+2*d)
		l = bsearchg(lm,x[i]-2*d)
		if l==0
			y = cld(max(h[i]-v[m],0),a)
		else
			y = cld(max(h[i]-v[m]+v[l],0),a)
		end
		if y > 0
			push!(lm,x[i])
			s += y
			push!(v,v[m]+y)
			m += 1
		end
	end
	println(s)
end

main()

Score : 600 points

Problem Statement

Silver Fox is fighting with N monsters.

The monsters are standing in a row, and we can assume them to be standing on a number line. The i-th monster, standing at the coordinate X_i, has the health of H_i.

Silver Fox can use bombs to attack the monsters.
Using a bomb at the coordinate x decreases the healths of all monsters between the coordinates x-D and x+D (inclusive) by A.
There is no way other than bombs to decrease the monster's health.

Silver Fox wins when all the monsters' healths become 0 or below.

Find the minimum number of bombs needed to win.

Constraints

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

0 \leq D \leq 10^9

1 \leq A \leq 10^9

0 \leq X_i \leq 10^9

1 \leq H_i \leq 10^9

X_i are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D A
X_1 H_1
:
X_N H_N

Output

Print the minimum number of bombs needed to win.

Sample Input 1

3 3 2
1 2
5 4
9 2

Sample Output 1

2

First, let us use a bomb at the coordinate 4 to decrease the first and second monsters' health by 2.

Then, use a bomb at the coordinate 6 to decrease the second and third monsters' health by 2.

Now, all the monsters' healths are 0.
We cannot make all the monsters' health drop to 0 or below with just one bomb.

Sample Input 2

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

Sample Output 2

5

We should use five bombs at the coordinate 5.

Sample Input 3

3 0 1
300000000 1000000000
100000000 1000000000
200000000 1000000000

Sample Output 3

3000000000

Watch out for overflow.


function main()
    n,m = map(x -> parse(Int, x), split(readline()))
    print(n == m ? "Yes" : "No")
end

main()

Score : 100 points

Problem Statement

Takahashi is participating in a programming contest, AXC001. He has just submitted his code to Problem A.

The problem has N test cases, all of which must be passed to get an AC verdict.

Takahashi's submission has passed M cases out of the N test cases.

Determine whether Takahashi's submission gets an AC.

Constraints

1 \leq N \leq 100

0 \leq M \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

If Takahashi's submission gets an AC, print Yes; otherwise, print No.

Sample Input 1

3 3

Sample Output 1

Yes

All three test cases have been passed, so his submission gets an AC.

Sample Input 2

3 2

Sample Output 2

No

Only two out of the three test cases have been passed, so his submission does not get an AC.

Sample Input 3

1 1

Sample Output 3

Yes


NM = readline()
if NM[1] == NM[end]
    println("Yes")
else
    println("No")
end


function parseInt(x)
    parse(Int, x)
end

function main()
    a,b = split(readline())
    print(min(a, b) ^ parseInt(max(a, b)))
end

main()

Score : 200 points

Problem Statement

Given are 1-digit positive integers a and b. Consider these two strings: the concatenation of b copies of the digit a, and the concatenation of a copies of the digit b. Which of these is lexicographically smaller?

Constraints

1 \leq a \leq 9

1 \leq b \leq 9

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the lexicographically smaller of the two strings. (If the two strings are equal, print one of them.)

Sample Input 1

4 3

Sample Output 1

3333

We have two strings 444 and 3333. Between them, 3333 is the lexicographically smaller.

Sample Input 2

7 7

Sample Output 2

7777777


N = parse(Int, readline())
P = parse.(Int, split(readline()))
minimum = P[1]
count = 0
for i in P
    if i <= minimum
        global minimum = i
        global count += 1
    end
end
println(count)

Score : 300 points

Problem Statement

Given is a permutation P_1, \ldots, P_N of 1, \ldots, N.
Find the number of integers i (1 \leq i \leq N) that satisfy the following condition:

For any integer j (1 \leq j \leq i), P_i \leq P_j.

Constraints

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

P_1, \ldots, P_N is a permutation of 1, \ldots, N.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 ... P_N

Output

Print the number of integers i that satisfy the condition.

Sample Input 1

5
4 2 5 1 3

Sample Output 1

3

i=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j holds for j = 1.

Similarly, i=5 does not satisfy the condition, either. Thus, there are three integers that satisfy the condition.

Sample Input 2

4
4 3 2 1

Sample Output 2

4

All integers i (1 \leq i \leq N) satisfy the condition.

Sample Input 3

6
1 2 3 4 5 6

Sample Output 3

1

Only i=1 satisfies the condition.

Sample Input 4

8
5 7 4 2 6 8 1 3

Sample Output 4

4

Sample Input 5

1
1

Sample Output 5

1


D=zeros(Int,10,10)
for i=1:parse(Int,readline())
	x=i
	while x>=10
		x=div(x,10)
	end
	D[x+1,i%10+1]+=1
end
ans=0
for i=1:10,j=1:10
	ans+=D[i,j]*D[j,i]
end
println(ans)

Score : 400 points

Problem Statement

Given is a positive integer N.

Find the number of pairs (A, B) of positive integers not greater than N that satisfy the following condition:

When A and B are written in base ten without leading zeros, the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

25

Sample Output 1

17

The following 17 pairs satisfy the condition: (1,1), (1,11), (2,2), (2,22), (3,3), (4,4), (5,5), (6,6), (7,7), (8,8), (9,9), (11,1), (11,11), (12,21), (21,12), (22,2), and (22,22).

Sample Input 2

1

Sample Output 2

1

Sample Input 3

100

Sample Output 3

108

Sample Input 4

2020

Sample Output 4

40812

Sample Input 5

200000

Sample Output 5

400000008


#=
B:
- Julia version:0.5.2
- Author: abap
- Date: 2020-01-12
=#
parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
N = parseInt(readline())
A = parseMap(split(readline()))
x = lcm(A)
ans :: BigInt
ans = 0
for i in A
	ans += x / i
end
anser = ans % (10^9 + 7)
println(Int64(anser))

Score : 500 points

Problem Statement

Given are N positive integers A_1,...,A_N.

Consider positive integers B_1, ..., B_N that satisfy the following condition.

Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds.

Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N.

Since the answer can be enormous, print the sum modulo (10^9 +7).

Constraints

1 \leq N \leq 10^4

1 \leq A_i \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the minimum possible value of B_1 + ... + B_N for B_1,...,B_N that satisfy the condition, modulo (10^9 +7).

Sample Input 1

3
2 3 4

Sample Output 1

13

Let B_1=6, B_2=4, and B_3=3, and the condition will be satisfied.

Sample Input 2

5
12 12 12 12 12

Sample Output 2

5

We can let all B_i be 1.

Sample Input 3

3
1000000 999999 999998

Sample Output 3

996989508

Print the sum modulo (10^9+7).


const N=parse(Int,readline())
const U=Int[]
const V=Int[]
const G=[Int[] for _=1:N]
for i=1:N-1
	u,v=map(x->parse(Int,x),split(readline()))
	push!(U,u)
	push!(V,v)
	push!(G[u],v)
	push!(G[v],u)
end
const depth=zeros(Int,N)
const subtree=zeros(Int,N)
function dfs(u,p,d)
	depth[u]=d
	subtree[u]=2^u
	for v=G[u]
		if v!=p
			subtree[u]+=dfs(v,u,d+1)
		end
	end
	subtree[u]
end
dfs(1,0,0)
const M=parse(Int,readline())
const check=zeros(Int,N-1)
for i=1:M
	a,b=map(x->parse(Int,x),split(readline()))
	test=2^a+2^b
	for j=1:N-1
		w=depth[U[j]]<depth[V[j]] ? V[j] : U[j]
		x=test&subtree[w]
		if x!=test&&x!=0
			check[j]+=2^(i-1)
		end
	end
end
function main()
	ans=0
	for i=0:2^M-1
		cnt=N-1
		for j=1:N-1
			if (check[j]&i)!=0
				cnt-=1
			end
		end
		now=2^cnt
		parity=0
		for j=0:M-1
			if (i>>j)%2==1
				parity+=1
			end
		end
		ans+=parity%2==0 ? now : -now
	end
	println(ans)
end
main()

Score : 600 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i.

Consider painting each of these edges white or black. There are 2^{N-1} such ways to paint the edges. Among them, how many satisfy all of the following M restrictions?

The i-th (1 \leq i \leq M) restriction is represented by two integers u_i and v_i, which mean that the path connecting Vertex u_i and Vertex v_i must contain at least one edge painted black.

Constraints

2 \leq N \leq 50

1 \leq a_i,b_i \leq N

The graph given in input is a tree.

1 \leq M \leq \min(20,\frac{N(N-1)}{2})

1 \leq u_i < v_i \leq N

If i \not= j, either u_i \not=u_j or v_i\not=v_j

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
M
u_1 v_1
:
u_M v_M

Output

Print the number of ways to paint the edges that satisfy all of the M conditions.

Sample Input 1

3
1 2
2 3
1
1 3

Sample Output 1

3

The tree in this input is shown below:

All of the M restrictions will be satisfied if Edge 1 and 2 are respectively painted (white, black), (black, white), or (black, black), so the answer is 3.

Sample Input 2

2
1 2
1
1 2

Sample Output 2

1

The tree in this input is shown below:

All of the M restrictions will be satisfied only if Edge 1 is painted black, so the answer is 1.

Sample Input 3

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

Sample Output 3

9

The tree in this input is shown below:

Sample Input 4

8
1 2
2 3
4 3
2 5
6 3
6 7
8 6
5
2 7
3 5
1 6
2 8
7 8

Sample Output 4

62

The tree in this input is shown below:


function main()

  H = parse(Int,readline())
  W = parse(Int,readline())
  N = parse(Int,readline())

  a = max(H,W)

  println(ceil(Int,N/a))

end

main()

Score : 100 points

Problem Statement

We have a grid with H rows and W columns, where all the squares are initially white.

You will perform some number of painting operations on the grid.
In one operation, you can do one of the following two actions:

Choose one row, then paint all the squares in that row black.

Choose one column, then paint all the squares in that column black.

At least how many operations do you need in order to have N or more black squares in the grid?
It is guaranteed that, under the conditions in Constraints, having N or more black squares is always possible by performing some number of operations.

Constraints

1 \leq H \leq 100

1 \leq W \leq 100

1 \leq N \leq H \times W

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H
W
N

Output

Print the minimum number of operations needed.

Sample Input 1

3
7
10

Sample Output 1

2

You can have 14 black squares in the grid by performing the "row" operation twice, on different rows.

Sample Input 2

14
12
112

Sample Output 2

8

Sample Input 3

2
100
200

Sample Output 3

2


function main()

  N = parse(Int,readline())
  R = [(0,0,0) for i in 1:N]

  for i in 1:N

    (a,b) = map(x -> parse(Int,x), split(readline()))
    R[i] = (a-b,a,a+b)

  end

  sort!(R, by = R -> R[2])

  count = N

  for i in 1:N-1

    if R[i][3] > R[i+1][1]
      count -= 1
      R[i+1] = (-10^10,-10^10,-10^10)
    end

  end

  println(count)

end

main()

Score : 200 points

Problem Statement

In a factory, there are N robots placed on a number line.
Robot i is placed at coordinate X_i and can extend its arms of length L_i in both directions, positive and negative.

We want to remove zero or more robots so that the movable ranges of arms of no two remaining robots intersect.
Here, for each i (1 \leq i \leq N), the movable range of arms of Robot i is the part of the number line between the coordinates X_i - L_i and X_i + L_i, excluding the endpoints.

Find the maximum number of robots that we can keep.

Constraints

1 \leq N \leq 100,000

0 \leq X_i \leq 10^9 (1 \leq i \leq N)

1 \leq L_i \leq 10^9 (1 \leq i \leq N)

If i \neq j, X_i \neq X_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 L_1
X_2 L_2
\vdots
X_N L_N

Output

Print the maximum number of robots that we can keep.

Sample Input 1

4
2 4
4 3
9 3
100 5

Sample Output 1

3

By removing Robot 2, we can keep the other three robots.

Sample Input 2

2
8 20
1 10

Sample Output 2

1

Sample Input 3

5
10 1
2 1
4 1
6 1
8 1

Sample Output 3

5


#=
C:
- Julia version:
- Author: abap
- Date: 2020-01-18
=#
N,K,S = parse.(split(readline()))
A = fill(1, N)
if N - K < S
for i in 1:K
	A[i] = S
end
for k in A
	print("$k ")
end
else
    A = fill(S + 1, N)
    for i in 1:K
        A[i] = S
	end
	for k in A
		print("$k ")
	end
end

println("")

Score : 400 points

Problem Statement

Given are three integers N, K, and S.

Find a sequence A_1, A_2, ..., A_N of N integers between 1 and 10^9 (inclusive) that satisfies the condition below.
We can prove that, under the conditions in Constraints, such a sequence always exists.

There are exactly K pairs (l, r) of integers such that 1 \leq l \leq r \leq N and A_l + A_{l + 1} + \cdots + A_r = S.

Constraints

1 \leq N \leq 10^5

0 \leq K \leq N

1 \leq S \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K S

Output

Print a sequence satisfying the condition, in the following format:

A_1 A_2 ... A_N

Sample Input 1

4 2 3

Sample Output 1

1 2 3 4

Two pairs (l, r) = (1, 2) and (3, 3) satisfy the condition in the statement.

Sample Input 2

5 3 100

Sample Output 2

50 50 50 30 70


Score : 100 points

Problem Statement

Given is a lowercase English letter C that is not z. Print the letter that follows C in alphabetical order.

Constraints

C is a lowercase English letter that is not z.

Input

Input is given from Standard Input in the following format:

C

Output

Print the letter that follows C in alphabetical order.

Sample Input 1

a

Sample Output 1

b

a is followed by b.

Sample Input 2

y

Sample Output 2

z

y is followed by z.


#=
C:
- Julia version:
- Author: abap
- Date: 2020-01-12
=#
parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
N,M = parseMap(split(readline()))
d = Dict()
wa = 0
ac = 0
for i in 1:M
	#println(d)
	p,s = split(readline())
	p = parseInt(p)
	#println("$p $s")
	if !(in(p,keys(d)))
		push!(d,p=>"wa")
	end
	if s == "WA" &&  d[p] == "wa"
		wa += 1
		#print("$(d[p]) なので、wa")
	elseif s == "AC" && d[p] == "wa"
		d[p] = "a"
		ac += 1
		#println("ac")
	end
end
println("$ac $wa")

Score : 300 points

Problem Statement

Takahashi participated in a contest on AtCoder.

The contest had N problems.

Takahashi made M submissions during the contest.

The i-th submission was made for the p_i-th problem and received the verdict S_i (AC or WA).

The number of Takahashi's correct answers is the number of problems on which he received an AC once or more.

The number of Takahashi's penalties is the sum of the following count for the problems on which he received an AC once or more: the number of WAs received before receiving an AC for the first time on that problem.

Find the numbers of Takahashi's correct answers and penalties.

Constraints

N, M, and p_i are integers.

1 \leq N \leq 10^5

0 \leq M \leq 10^5

1 \leq p_i \leq N

S_i is AC or WA.

Input

Input is given from Standard Input in the following format:

N M
p_1 S_1
:
p_M S_M

Output

Print the number of Takahashi's correct answers and the number of Takahashi's penalties.

Sample Input 1

2 5
1 WA
1 AC
2 WA
2 AC
2 WA

Sample Output 1

2 2

In his second submission, he received an AC on the first problem for the first time. Before this, he received one WA on this problem.

In his fourth submission, he received an AC on the second problem for the first time. Before this, he received one WA on this problem.

Thus, he has two correct answers and two penalties.

Sample Input 2

100000 3
7777 AC
7777 AC
7777 AC

Sample Output 2

1 0

Note that it is pointless to get an AC more than once on the same problem.

Sample Input 3

6 0

Sample Output 3

0 0


#=
C:
- Julia version:
- Author: abap
- Date: 2020-01-12
=#
parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
N,M = parseMap(split(readline()))
d = Dict()
wa = 0
ac = 0
for i in 1:M
	p,s = split(readline())
	p = parseInt(p)
	if !(in(7777,keys(d)))
		push!(d,p=>"no")
	end
	if s == "WA" && (d[p] == "no" || d[p] == "wa")
		wa += 1
	elseif s == "AC" && (d[p] == "no" || d[p] == "wa")
		d[p] = "a"
		ac += 1
	end
end
println("$ac $wa")


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	n,m = readline() |> split |> parseMap
	a = Tuple{Int,Int}[(0,0) for i in 1:n]
	ac = Dict{Int,Int}()
	wa = 0
	for i in 1:m
		p,x = readline() |> chomp |> split
		p = parseInt(p)
		if x=="AC"
			ac[p]=1
		else
			wa += 1
		end
	end
	println(length(ac)," ",wa)
end

main()


using DataStructures
const double = Float64
const int = Int64

parseint(x) = parse(int, x)
readint() = map(parseint, split(readline()))

function main()
  H,W = readint()
  S = String[]
  for _ in 1:H
    s = readline()
    append!(S,[s])
  end

  Lmax = H*W + 1
  d = Array{int,4}(undef, H,W,H,W)
  d .= H*W + 1

  mat = Array{int,4}(undef,H,W,H,W)
  mat .= 0

  for i in 1:H, j in 1:W
    S[i][j] == '#' && continue

    if i+1 <=H && S[i+1][j] == '.'
      mat[i,j,i+1,j] = 1
      mat[i+1,j,i,j] = 1
    end
    if j+1 <= W &&S[i][j+1] == '.'
      mat[i,j,i,j+1] = 1
      mat[i,j+1,i,j] = 1
    end
  end

  for i1 in 1:H, j1 in 1:W
    for i2 in 1:H, j2 in 1:W
      i1 == i2 && j1 == j2 && (d[i1,j1,i2,j2]=0)
      if mat[i1,j1, i2, j2] == 1
        d[i1,j1,i2,j2] = 1
      end
    end
  end
  for i1 in 1:H, j1 in 1:W
    for i2 in 1:H, j2 in 1:W
      for i3 in 1:H, j3 in 1:W
        d[i2,j2,i3,j3] = min(d[i2,j2,i3,j3] , d[i2,j2,i1,j1] + d[i3,j3,i1,j1])
      end
    end
  end

  s = 0
  for i in 1:H, j in 1:W
    for i2 in 1:H, j2 in 1:W
      if d[i,j,i2,j2] > s && d[i,j,i2,j2]<Lmax
        s = d[i,j,i2,j2]
      end
    end
  end
  println(s)
  #println(S[2][4])
  #println(S)
end

main()

Score : 400 points

Problem Statement

Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.

The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.


f()=parse.(split(readline()))
N,K=f()
A=sort(f())
S=0
C=1
M=10^9+7
for k=K:N
	S+=C*(A[k]-A[N+1-k])
	C=C*k%M*invmod(k-K+1,M)%M
end
show(S%M)

Score : 500 points

Problem Statement

For a finite set of integers X, let f(X)=\max X - \min X.

Given are N integers A_1,...,A_N.

We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over all those ways.

Since the answer can be enormous, print it \bmod (10^9+7).

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

|A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 ... A_N

Output

Print the answer \bmod (10^9+7).

Sample Input 1

4 2
1 1 3 4

Sample Output 1

11

There are six ways to choose S: \{1,1\},\{1,3\},\{1,4\},\{1,3\},\{1,4\}, \{3,4\} (we distinguish the two 1s). The value of f(S) for these choices are 0,2,3,2,3,1, respectively, for the total of 11.

Sample Input 2

6 3
10 10 10 -10 -10 -10

Sample Output 2

360

There are 20 ways to choose S. In 18 of them, f(S)=20, and in 2 of them, f(S)=0.

Sample Input 3

3 1
1 1 1

Sample Output 3

0

Sample Input 4

10 6
1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0

Sample Output 4

999998537

Print the sum \bmod (10^9+7).


Score : 600 points

Problem Statement

Given are N points (x_i, y_i) in a two-dimensional plane.

Find the minimum radius of a circle such that all the points are inside or on it.

Constraints

2 \leq N \leq 50

0 \leq x_i \leq 1000

0 \leq y_i \leq 1000

The given N points are all different.

The values in input are all integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the minimum radius of a circle such that all the N points are inside or on it.

Your output will be considered correct if the absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

2
0 0
1 0

Sample Output 1

0.500000000000000000

Both points are contained in the circle centered at (0.5,0) with a radius of 0.5.

Sample Input 2

3
0 0
0 1
1 0

Sample Output 2

0.707106781186497524

Sample Input 3

10
10 9
5 9
2 0
0 0
2 7
3 3
2 5
10 0
3 7
1 9

Sample Output 3

6.726812023536805158

If the absolute or relative error from our answer is at most 10^{-6}, the output will be considered correct.


parseInt(x::String) = parse(Int, x)
parseInt(x::SubString{String}) = parse(Int, x)
parseInt(x::Char) = parse(Int, x)
parseInt(x::Float64) = trunc(Int, x)
parseFloat(x::String) = parse(Float64, x)
parseFloat(x::Int) = trunc(Float64, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
    n=parseInt(readline())
    st=[split(readline()) for i in 1:n]
    x=readline()
    ans=0
    flg=false
    for i in 1:n
        if flg
            ans+=parseInt(st[i][2])
        end
        if st[i][1]==x
            flg=true
        end
    end
    println(ans)
end
main()

Score : 200 points

Problem Statement

Niwango created a playlist of N songs.
The title and the duration of the i-th song are s_i and t_i seconds, respectively.
It is guaranteed that s_1,\ldots,s_N are all distinct.

Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, without any pause in between.)
However, he fell asleep during his work, and he woke up after all the songs were played.
According to his record, it turned out that he fell asleep at the very end of the song titled X.

Find the duration of time when some song was played while Niwango was asleep.

Constraints

1 \leq N \leq 50

s_i and X are strings of length between 1 and 100 (inclusive) consisting of lowercase English letters.

s_1,\ldots,s_N are distinct.

There exists an integer i such that s_i = X.

1 \leq t_i \leq 1000

t_i is an integer.

Input

Input is given from Standard Input in the following format:

N
s_1 t_1
\vdots
s_{N} t_N
X

Output

Print the answer.

Sample Input 1

3
dwango 2
sixth 5
prelims 25
dwango

Sample Output 1

30

While Niwango was asleep, two songs were played: sixth and prelims.

The answer is the total duration of these songs, 30.

Sample Input 2

1
abcde 1000
abcde

Sample Output 2

0

No songs were played while Niwango was asleep.

In such a case, the total duration of songs is 0.

Sample Input 3

15
ypnxn 279
kgjgwx 464
qquhuwq 327
rxing 549
pmuduhznoaqu 832
dagktgdarveusju 595
wunfagppcoi 200
dhavrncwfw 720
jpcmigg 658
wrczqxycivdqn 639
mcmkkbnjfeod 992
htqvkgkbhtytsz 130
twflegsjz 467
dswxxrxuzzfhkp 989
szfwtzfpnscgue 958
pmuduhznoaqu

Sample Output 3

6348


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	n = readline() |> parseInt
	d = Dict{String,Int}()
	ct = 0
	for i in 1:n
		s,t = readline() |> chomp |> split
		ct += parseInt(t)
		d[s]=ct
	end
	x = readline() |> chomp
	println(ct-d[x])
end

main()


function main()

  N = parse(Int,readline())
  S = split(chomp(readline()),"")

  count = 0

  for i in 1:N-2

    if S[i] == "A" && S[i+1] == "B" && S[i+2] == "C"
      count += 1
    end

  end

  println(count)

end

main()

Score : 200 points

Problem Statement

We have a string S of length N consisting of uppercase English letters.

How many times does ABC occur in S as contiguous subsequences (see Sample Inputs and Outputs)?

Constraints

3 \leq N \leq 50

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print number of occurrences of ABC in S as contiguous subsequences.

Sample Input 1

10
ZABCDBABCQ

Sample Output 1

2

Two contiguous subsequences of S are equal to ABC: the 2-nd through 4-th characters, and the 7-th through 9-th characters.

Sample Input 2

19
THREEONEFOURONEFIVE

Sample Output 2

0

No contiguous subsequences of S are equal to ABC.

Sample Input 3

33
ABCCABCBABCCABACBCBBABCBCBCBCABCB

Sample Output 3

5


parseInt(x) = parse(Int, x)
parseBigInt(x) = parse(BigInt, x)
parseFloat(x) = parse(Float64, x)
parseBigFloat(x) = parse(BigFloat, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

arr=Vector{Vector{Int}}()
function dfs(n,array,cnt)
    if n==cnt
        push!(arr,array)
        return 0
    end
    for i in 1:n
        if !(i in array)
            dfs(n,vcat(array,[i]),cnt+1)
        end
    end
end

function main()
    n=parseInt(readline())
    p=parseMap(split(readline()))
    q=parseMap(split(readline()))
    dfs(n,Vector{Int}(),0)
    a=findfirst(x->x==p,arr)
    b=findfirst(x->x==q,arr)
    println(abs(a-b))
end
main()

Score : 300 points

Problem Statement

We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N)).

There are N! possible permutations of size N. Among them, let P and Q be the a-th and b-th lexicographically smallest permutations, respectively. Find |a - b|.

Notes

For two sequences X and Y, X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k.

Constraints

2 \leq N \leq 8

P and Q are permutations of size N.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 ... P_N
Q_1 Q_2 ... Q_N

Output

Print |a - b|.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

There are 6 permutations of size 3: (1,~2,~3), (1,~3,~2), (2,~1,~3), (2,~3,~1), (3,~1,~2), and (3,~2,~1). Among them, (1,~3,~2) and (3,~1,~2) come 2-nd and 5-th in lexicographical order, so the answer is |2 - 5| = 3.

Sample Input 2

8
7 3 5 4 2 1 6 8
3 8 2 5 4 6 7 1

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

0


parseline(str=readline()) = parse.(Int, split(str))
function SemiCommonMultiple()
    N, M = parseline()
    A = parseline()
    a = div.(A, 2)
    temp = a
    zero = zeros(Int, N)
    while temp≠zero
        temp_ = temp.%2
        if 0 in temp_
            temp_==zero && (temp = div.(temp, 2); continue)
            return println(0)
        else
            break
        end
    end
    X = lcm(a)
    println(X>M ? 0 : (M - X)÷2X + 1)
end
SemiCommonMultiple()

Score : 400 points

Problem Statement

Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M.

Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N):

There exists a non-negative integer p such that X= a_k \times (p+0.5).

Find the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^9

2 \leq a_i \leq 10^9

a_i is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 a_2 ... a_N

Output

Print the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Sample Input 1

2 50
6 10

Sample Output 1

2

15 = 6 \times 2.5

15 = 10 \times 1.5

45 = 6 \times 7.5

45 = 10 \times 4.5

Thus, 15 and 45 are semi-common multiples of A. There are no other semi-common multiples of A between 1 and 50, so the answer is 2.

Sample Input 2

3 100
14 22 40

Sample Output 2

0

The answer can be 0.

Sample Input 3

5 1000000000
6 6 2 6 2

Sample Output 3

166666667


function main()
	N,M=map(x->parse(Int,x),split(readline()))
	g=0
	c=-1
	for a=map(x->parse(Int,x),split(readline()))
		a>>=1
		g=gcd(g,a)
		t=0
		while a%2==0
			a>>=1
			t+=1
		end
		if c<0
			c=t
		elseif c!=t
			println(0)
			exit()
		end
	end
	if g>M
		println(0)
	else
		t=div(M,g)
		println(div(t+1,2))
	end
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	n,m = readline() |> split |> parseMap
	a = readline() |> split |> parseMap
	b = [a[i]>>1 for i in 1:n]
	x = lcm(b)
	f = 10^18
	for i in 1:n
		if b[i]%2==0
			f = min(f,b[i])
		end
	end
	println(f==10^18?(div(m,x)+1)>>1:(div(min(m,2*f),x)+1)>>1)
end

main()


function Zalgo(s)
	N=length(s)
	ret=zeros(Int,N)
	ret[1]=N
	i=1
	j=0
	while i<N
		while i+j<N&&s[j+1]==s[i+j+1]
			j+=1
		end
		ret[i+1]=j
		if j==0
			i+=1
			continue
		end
		k=1
		while i+k<N&&k+ret[k+1]<j
			ret[i+k+1]=ret[k+1]
			k+=1
		end
		i+=k
		j-=k
	end
	ret
end
function main()
	N=parse(Int,readline())
	A=map(x->parse(Int,x),split(readline()))
	B=map(x->parse(Int,x),split(readline()))
	a=zeros(Int,3N)
	for i=1:N
		a[i]=B[i]$B[mod1(i+1,N)]
		a[i+N]=a[i+2N]=A[i]$A[mod1(i+1,N)]
	end
	L=Zalgo(a)
	for k=1:N
		if L[k+N]>=N
			println("$(k-1) $(A[k]$B[1])")
		end
	end
end
main()

Score : 600 points

Problem Statement

Given are two sequences a=\{a_0,\ldots,a_{N-1}\} and b=\{b_0,\ldots,b_{N-1}\} of N non-negative integers each.

Snuke will choose an integer k such that 0 \leq k < N and an integer x not less than 0, to make a new sequence of length N, a'=\{a_0',\ldots,a_{N-1}'\}, as follows:

a_i'= a_{i+k \mod N}\ XOR \ x

Find all pairs (k,x) such that a' will be equal to b.

What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.

For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

Constraints

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

0 \leq a_i,b_i < 2^{30}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_0 a_1 ... a_{N-1}
b_0 b_1 ... b_{N-1}

Output

Print all pairs (k, x) such that a' and b will be equal, using one line for each pair, in ascending order of k (ascending order of x for pairs with the same k).

If there are no such pairs, the output should be empty.

Sample Input 1

3
0 2 1
1 2 3

Sample Output 1

1 3

If (k,x)=(1,3),

a_0'=(a_1\ XOR \ 3)=1

a_1'=(a_2\ XOR \ 3)=2

a_2'=(a_0\ XOR \ 3)=3

and we have a' = b.

Sample Input 2

5
0 0 0 0 0
2 2 2 2 2

Sample Output 2

0 2
1 2
2 2
3 2
4 2

Sample Input 3

6
0 1 3 7 6 4
1 5 4 6 2 3

Sample Output 3

2 2
5 5

Sample Input 4

2
1 2
0 0

Sample Output 4

No pairs may satisfy the condition.


Score : 100 points

Problem Statement

Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string.

Constraints

S and T are strings consisting of lowercase English letters.

The lengths of S and T are between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S T

Output

Print the resulting string.

Sample Input 1

oder atc

Sample Output 1

atcoder

When S = oder and T = atc, concatenating T and S in this order results in atcoder.

Sample Input 2

humu humu

Sample Output 2

humuhumu


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    a,b,k=parseMap(split(readline()))
    a,b=max(0,a-k),ifelse(a<=k,max(0,b-(k-a)),b)
    println("$a $b")
end
main()

Score : 200 points

Problem Statement

Takahashi has A cookies, and Aoki has B cookies.
Takahashi will do the following action K times:

If Takahashi has one or more cookies, eat one of his cookies.

Otherwise, if Aoki has one or more cookies, eat one of Aoki's cookies.

If they both have no cookies, do nothing.

In the end, how many cookies will Takahashi and Aoki have, respectively?

Constraints

0 \leq A \leq 10^{12}

0 \leq B \leq 10^{12}

0 \leq K \leq 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the numbers of Takahashi's and Aoki's cookies after K actions.

Sample Input 1

2 3 3

Sample Output 1

0 2

Takahashi will do the following:

He has two cookies, so he eats one of them.

Now he has one cookie left, and he eats it.

Now he has no cookies left, but Aoki has three, so Takahashi eats one of them.

Thus, in the end, Takahashi will have 0 cookies, and Aoki will have 2.

Sample Input 2

500000000000 500000000000 1000000000000

Sample Output 2

0 0

Watch out for overflows.


function check(n)

  for i in 2:round(Int,sqrt(n))

    if n % i == 0
      return false
    end

  end

  return true

end

function main()

  X = parse(Int, readline())

  prime = false

  while prime == false

	prime = check(X)
    X += 1

  end

  println(X-1)

end

main()

Score: 300 points

Problem Statement

Find the minimum prime number greater than or equal to X.

Notes

A prime number is an integer greater than 1 that cannot be evenly divided by any positive integer except 1 and itself.

For example, 2, 3, and 5 are prime numbers, while 4 and 6 are not.

Constraints

2 \le X \le 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the minimum prime number greater than or equal to X.

Sample Input 1

20

Sample Output 1

23

The minimum prime number greater than or equal to 20 is 23.

Sample Input 2

2

Sample Output 2

2

X itself can be a prime number.

Sample Input 3

99992

Sample Output 3

100003


N=parse(readline())
while 1>0
  f=0
  for i=2:isqrt(N)
    if N%i==0
      f+=1
    end
  end
  if f==0
    println(N)
    exit()
  end
  N+=1
end


parseline(str=readline()) = parse.(Int, split(str))
function PredictionAndRestriction()
    N, K = parseline()
    R, S, P = parseline()
    score = zeros(Int, N)
    T = readline()
    for n in 1:N
        if T[n]=='r'
            score[n] = P
        elseif T[n]=='s'
            score[n] = R
        else
            score[n] = S
        end
    end
    for k in 1:K
        now = k + K
        while now ≤ N
            T[now-K] == T[now] && (score[now]=0)
            now += K
        end
    end
    println(sum(score))
end
PredictionAndRestriction()

Score : 400 points

Problem Statement

At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:

The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)

Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):

R points for winning with Rock;

S points for winning with Scissors;

P points for winning with Paper.

However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.)

Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.

The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is r, the machine will play Rock in the i-th round. Similarly, p and s stand for Paper and Scissors, respectively.

What is the maximum total score earned in the game by adequately choosing the hand to play in each round?

Notes

In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand.

If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins;

if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins;

if a player chooses Paper and the other chooses Rock, the player choosing Paper wins;

if both players play the same hand, it is a draw.

Constraints

2 \leq N \leq 10^5

1 \leq K \leq N-1

1 \leq R,S,P \leq 10^4

N,K,R,S, and P are all integers.

|T| = N

T consists of r, p, and s.

Input

Input is given from Standard Input in the following format:

N K
R S P
T

Output

Print the maximum total score earned in the game.

Sample Input 1

5 2
8 7 6
rsrpr

Sample Output 1

27

The machine will play {Rock, Scissors, Rock, Paper, Rock}.

We can, for example, play {Paper, Rock, Rock, Scissors, Paper} against it to earn 27 points.
We cannot earn more points, so the answer is 27.

Sample Input 2

7 1
100 10 1
ssssppr

Sample Output 2

211

Sample Input 3

30 5
325 234 123
rspsspspsrpspsppprpsprpssprpsr

Sample Output 3

4996


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    n,k=parseMap(split(readline()))
    r,s,p=parseMap(split(readline()))
    t=chomp(readline())
    good=""
    win=Dict{Char,Char}('r'=>'p','s'=>'r','p'=>'s')
    point=Dict{Char,Int}('r'=>r,'s'=>s,'p'=>p)
    ans=0
    good=join([win[i] for i in t])
    ok=[true for i in 1:n]
    for i in 1:n
        if i<=k || good[i-k]!=good[i] || !ok[i-k]
            ans+=point[good[i]]
        else
            ok[i]=false
        end
    end
    println(ans)
end
main()


parseInt(x) = parse(Int,x)
N,A,B= parseInt.(split(readline()))

println(min(A-1,N-B) + 1 + cld((B-A-1),2))

Score : 300 points

Problem Statement

2N players are running a competitive table tennis training on N tables numbered from 1 to N.

The training consists of rounds.
In each round, the players form N pairs, one pair per table.
In each pair, competitors play a match against each other.
As a result, one of them wins and the other one loses.

The winner of the match on table X plays on table X-1 in the next round,
except for the winner of the match on table 1 who stays at table 1.

Similarly, the loser of the match on table X plays on table X+1 in the next round,
except for the loser of the match on table N who stays at table N.

Two friends are playing their first round matches on distinct tables A and B.
Let's assume that the friends are strong enough to win or lose any match at will.
What is the smallest number of rounds after which the friends can get to play a match against each other?

Constraints

2 \leq N \leq 10^{18}

1 \leq A < B \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the smallest number of rounds after which the friends can get to play a match against each other.

Sample Input 1

5 2 4

Sample Output 1

1

If the first friend loses their match and the second friend wins their match, they will both move to table 3 and play each other in the next round.

Sample Input 2

5 2 3

Sample Output 2

2

If both friends win two matches in a row, they will both move to table 1.


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	n,a,b = readline() |> split |> parseMap
	if a%2==b%2
		println(min(n-min(a,b)-1,max(a,b)-1,(b-a)>>1))
	else
		println(min(n-min(a,b)-1,max(a,b)-1))
	end
end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	n = readline() |> parseInt
	if n%3 != 0
		println(-1)
	else
		for i in 1:n
			for j in 1:n-1
				if (i%3==0&&j%3!=0)||(i%3!=0&&j%3==0)
					print("a ")
				else
					print(". ")
				end
			end
			if (i%3==0&&n%3!=0)||(i%3!=0&&n%3==0)
				println("a")
			else
				println(".")
			end
		end
	end
end

main()

Score : 900 points

Problem Statement

Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid.
Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.

For each row of the grid, let's define its quality as the number of domino pieces that cover at least one square in this row.
We define the quality of each column similarly.

Find a way to put at least one domino piece on the grid so that the quality of every row is equal to the quality of every column,
or determine that such a placement doesn't exist.

Constraints

2 \le N \le 1000

Input

Input is given from Standard Input in the following format:

N

Output

If the required domino placement doesn't exist, print a single integer -1.

Otherwise, output your placement as N strings of N characters each.
If a square is not covered, the corresponding character must be . (a dot).
Otherwise, it must contain a lowercase English letter.
Squares covered by the same domino piece must contain the same letter.
If two squares have a common side but belong to different pieces, they must contain different letters.

Sample Input 1

6

Sample Output 1

aabb..
b..zz.
ba....
.a..aa
..a..b
..a..b

The quality of every row and every column is 2.

Sample Input 2

2

Sample Output 2

-1


function main()
  a = parse(Int, readline())
  b = parse(Int, readline())
  println(6-a-b)
end

main()

Score: 100 points

Problem Statement

Takahashi is solving quizzes. He has easily solved all but the last one.

The last quiz has three choices: 1, 2, and 3.

With his supernatural power, Takahashi has found out that the choices A and B are both wrong.

Print the correct choice for this problem.

Constraints

Each of the numbers A and B is 1, 2, or 3.

A and B are different.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print the correct choice.

Sample Input 1

3
1

Sample Output 1

2

When we know 3 and 1 are both wrong, the correct choice is 2.

Sample Input 2

1
2

Sample Output 2

3


a = parse(Int, readline())
b = parse(Int, readline())
println(6-a-b)


n=parse(Int,readline())
a,b=split(readline())
for i=1:n
  print(a[i],b[i])
end

Score : 200 points

Problem Statement

Given are strings s and t of length N each, both consisting of lowercase English letters.

Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of S, the N-th character of T. Print this new string.

Constraints

1 \leq N \leq 100

|S| = |T| = N

S and T are strings consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S T

Output

Print the string formed.

Sample Input 1

2
ip cc

Sample Output 1

icpc

Sample Input 2

8
hmhmnknk uuuuuuuu

Sample Output 2

humuhumunukunuku

Sample Input 3

5
aaaaa aaaaa

Sample Output 3

aaaaaaaaaa


Score : 300 points

Problem Statement

Takahashi is organizing a party.

At the party, each guest will receive one or more snack pieces.

Takahashi predicts that the number of guests at this party will be A or B.

Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted.

We assume that a piece cannot be divided and distributed to multiple guests.

Constraints

1 \leq A, B \leq 10^5

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of pieces that can be evenly distributed to the guests in both of the cases with A guests and B guests.

Sample Input 1

2 3

Sample Output 1

6

When we have six snack pieces, each guest can take three pieces if we have two guests, and each guest can take two if we have three guests.

Sample Input 2

123 456

Sample Output 2

18696

Sample Input 3

100000 99999

Sample Output 3

9999900000


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	a,b = readline() |> split |> parseMap
	println(lcm(a,b))
end

main()


function main()

  N = parse(Int, readline())
  a = map(x -> parse(Int, x), split(readline()))

  cnt = 0
  check  = 1

  for i in a
    if i == check
      check += 1
    else
      cnt += 1
    end
  end

  if cnt == N
    println(-1)
  else
    println(cnt)
  end

end

main()

Score : 400 points

Problem Statement

We have N bricks arranged in a row from left to right.

The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it.

Among them, you can break at most N-1 bricks of your choice.

Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of those brick from the left has the integer i written on it.

Find the minimum number of bricks you need to break to satisfy Snuke's desire. If his desire is unsatisfiable, print -1 instead.

Constraints

All values in input are integers.

1 \leq N \leq 200000

1 \leq a_i \leq N

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of bricks that need to be broken to satisfy Snuke's desire, or print -1 if his desire is unsatisfiable.

Sample Input 1

3
2 1 2

Sample Output 1

1

If we break the leftmost brick, the remaining bricks have integers 1 and 2 written on them from left to right, in which case Snuke will be satisfied.

Sample Input 2

3
2 2 2

Sample Output 2

-1

In this case, there is no way to break some of the bricks to satisfy Snuke's desire.

Sample Input 3

10
3 1 4 1 5 9 2 6 5 3

Sample Output 3

7

Sample Input 4

1
1

Sample Output 4

0

There may be no need to break the bricks at all.


N=parse(readline())
c=1
for a=map(x->parse(Int,x),split(readline()))
  if c==a
    c+=1
  end
end
println(c==1 ? -1 : N-c+1)


parseInt(x) = parse(Int, x)
a,b,c = parseInt.(split(readline()))
if a + b + c >= 22
    println("bust")
else
    println("win")
end

Score : 100 points

Problem Statement

Given are three integers A_1, A_2, and A_3.

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Constraints

1 \leq A_i \leq 13 \ \ (i=1,2,3)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Sample Input 1

5 7 9

Sample Output 1

win

5+7+9=21, so print win.

Sample Input 2

13 7 2

Sample Output 2

bust

13+7+2=22, so print bust.


xor(a,b)=a$b
N=parse(Int,readline())
A=zeros(Int,N)
B=zeros(Int,N)
for i=1:N
	a=parse(Int,readline())
	for _=1:a
		x,y=map(x->parse(Int,x),split(readline()))
		if y==1
			A[i]=xor(A[i],2^(x-1))
		else
			B[i]=xor(B[i],2^(x-1))
		end
	end
end
ans=0
for m=0:2^N-1
	t=m
	f=(2^N-1)&~m
	cnt=0
	for i=1:N
		if (m>>(i-1))%2==1
			t=t|A[i]
			f=f|B[i]
			cnt+=1
		end
	end
	if (t&f)==0
		ans=max(ans,cnt)
	end
end
println(ans)

Score : 300 points

Problem Statement

There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.

Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony says Person x_{ij} is honest; if y_{ij} = 0, it says Person x_{ij} is unkind.

How many honest persons can be among those N people at most?

Constraints

All values in input are integers.

1 \leq N \leq 15

0 \leq A_i \leq N - 1

1 \leq x_{ij} \leq N

x_{ij} \neq i

x_{ij_1} \neq x_{ij_2} (j_1 \neq j_2)

y_{ij} = 0, 1

Input

Input is given from Standard Input in the following format:

N
A_1
x_{11} y_{11}
x_{12} y_{12}
:
x_{1A_1} y_{1A_1}
A_2
x_{21} y_{21}
x_{22} y_{22}
:
x_{2A_2} y_{2A_2}
:
A_N
x_{N1} y_{N1}
x_{N2} y_{N2}
:
x_{NA_N} y_{NA_N}

Output

Print the maximum possible number of honest persons among the N people.

Sample Input 1

3
1
2 1
1
1 1
1
2 0

Sample Output 1

2

If Person 1 and Person 2 are honest and Person 3 is unkind, we have two honest persons without inconsistencies, which is the maximum possible number of honest persons.

Sample Input 2

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

Sample Output 2

0

Assuming that one or more of them are honest immediately leads to a contradiction.

Sample Input 3

2
1
2 0
1
1 0

Sample Output 3

1


#=
C:
- Julia version:
- Author: abap
- Date: 2019-12-21
=#

function return_all_pettern(x)  #bit全探索
    count_pettern = x ^ 2
    b = []
    for i in 0:count_pettern - 1
        bit = bin(i, x)
        bits = []
        for j in 1:x
            push!(bits, bit[j])
        end
        bits = [bits .== '1']
        push!(b, bits)
    end
    #println(length(b))
    return  b
end

function main()
XY = Dict{Int64, Array{Any,1}}() # xıとyıの格納先
N = parse(Int,readline())
for i in 1:N
    A = parse(Int,readline())
    for j in  1:A
       xy = parse.(split(readline()))
       xy[2] = xy[2] == 1
       push!(XY,i=>xy)       # i = 発言者 xy = 主張
    end
end
petterns = return_all_pettern(length(keys(XY)))  # 全ての部分集合を取得
res_said = []
for i in 1:length(petterns)               # それぞれの部分集合についての結果の格納先
    push!(res_said,[])
end
for jj in 1:length(petterns)        # 特定の格納先に入れるためにインデックスを回す
    pettern = petterns[jj]
    honest_list = collect(1:N)[sum(pettern)]
    for k in honest_list
        push!(res_said[jj],[k,1])      # 発言している人は本物
        push!(res_said[jj], [XY[k][1],Bool(XY[k][2]) ]  ) # 本物の言っている人も本物
    end
end
global kari_ans = []
for i in 1:length(petterns)               # それぞれの仮の答えについての結果の格納先
    push!(kari_ans,[])
end

for kk in 1:length(petterns)        # 特定の格納先に入れるためにインデックスを回す
    res = res_said[kk]
    if res == []
        ans = 0
    else
        for ik in res
            push!(kari_ans[kk],[ik[1],ik[2]])
        end
    end
end
ans_list  = []
for kari in kari_ans
    #println(kari)
    honest_count = 0
    kari = unique(kari)
    for i in kari  # それぞれの結果について検証する
        #println(i)
        if i[2] == 0
            another_ans = [i[1],1]  # 違う答えがないかチェック
        else
            another_ans = [i[1],0]
            #=count = 0
            for jj in kari
                if jj == i
                    count += 1
                end
            end
            if count == 1
                honest_count += 1 # 同じ答えが何回もあるときはカウントしない
            end=#
        end
        if another_ans in kari
            honest_count = 0
            break
        end
    end
    push!(ans_list,honest_count)
end
println(maximum(ans_list))
end

main()


function count(i,A)
	ret=0
	for a=A
		ret+=(a>>i)%2
	end
	ret
end
function main()
	N=parse(Int,readline())
	A=map(x->parse(Int,x),split(readline()))
	ans=0
	mod=10^9+7
	for i=59:-1:0
		c=count(i,A)
		ans=(ans*2+c*(N-c))%mod
	end
	println(ans)
end
main()

Score : 400 points

Problem Statement

We have N integers. The i-th integer is A_i.

Find \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.

For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

Constraints

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

0 \leq A_i < 2^{60}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the value \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

6

We have (1\mbox{ XOR } 2)+(1\mbox{ XOR } 3)+(2\mbox{ XOR } 3)=3+2+1=6.

Sample Input 2

10
3 1 4 1 5 9 2 6 5 3

Sample Output 2

237

Sample Input 3

10
3 14 159 2653 58979 323846 2643383 27950288 419716939 9375105820

Sample Output 3

103715602

Print the sum modulo (10^9+7).


function  parse_int(x)
    parse(Int, x)
end
function  MAP()
    map(parse_int, split(readline(), " "))
end
function intinput()
    parse(Int, readline())
end
function solve()
    H, W = MAP()
    A = reshape(MAP(), 1, W)
    for i = 1:H-1
        A = [A; reshape(MAP(), 1, W)]
    end
    B = reshape(MAP(), 1, W)
    for i = 1:H-1
        B = [B; reshape(MAP(), 1, W)]
    end
    dp = falses(H, W, 12601)
    dp[1, 1, abs(A[1, 1] - B[1, 1]) + 1] = true
    for i = 2:H
        for k = 1:12601
            difference = abs(A[i, 1] - B[i, 1])
            if dp[i - 1, 1, k]
                dp[i, 1, k + difference] = true
                dp[i, 1, abs(k - 1 - difference) + 1] = true
            end
        end
    end
    for j = 2:W
        for k = 1:12601
            difference = abs(A[1, j] - B[1, j])
            if dp[1, j - 1, k]
                dp[1, j, k + difference] = true
                dp[1, j, abs(k - 1 - difference) + 1] = true
            end
        end
    end
    for i = 2:H, j = 2:W
        difference = abs(A[i, j] - B[i, j])
        for k = 1:12601
            if dp[i - 1, j, k] || dp[i, j - 1, k]
                dp[i, j, k + difference] = true
                dp[i, j, abs(k - 1 - difference) + 1] = true
            end
        end
    end
    ans = 0
    for i = 1:12601
        if dp[H, W, i]
            ans = i
            break
        end
    end
    println("$(ans - 1)")
end
solve()

Score : 500 points

Problem Statement

We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.

The square (i, j) has two numbers A_{ij} and B_{ij} written on it.

First, for each square, Takahashi paints one of the written numbers red and the other blue.

Then, he travels from the square (1, 1) to the square (H, W). In one move, he can move from a square (i, j) to the square (i+1, j) or the square (i, j+1). He must not leave the grid.

Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares (1, 1) and (H, W).

Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it.

Find the minimum unbalancedness possible.

Constraints

2 \leq H \leq 80

2 \leq W \leq 80

0 \leq A_{ij} \leq 80

0 \leq B_{ij} \leq 80

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W
A_{11} A_{12} \ldots A_{1W}
:
A_{H1} A_{H2} \ldots A_{HW}
B_{11} B_{12} \ldots B_{1W}
:
B_{H1} B_{H2} \ldots B_{HW}

Output

Print the minimum unbalancedness possible.

Sample Input 1

2 2
1 2
3 4
3 4
2 1

Sample Output 1

0

By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are 3+3+1=7 and 1+2+4=7, respectively, for the unbalancedness of 0.

Sample Input 2

2 3
1 10 80
80 10 1
1 2 3
4 5 6

Sample Output 2

2


function  parse_int(x)
    parse(Int, x)
end
function  MAP()
    map(parse_int, split(readline(), " "))
end
function intinput()
    parse(Int, readline())
end
function solve()
    H, W = MAP()
    a = MAP()
    a = reshape(a, 1, W)
    A = copy(a)
    for i = 1:H-1
        a = MAP()
        a = reshape(a, 1, W)
        A = [A; a]
    end
    b = MAP()
    b = reshape(b, 1, W)
    B = copy(b)
    for i = 1:H-1
        b = MAP()
        b = reshape(b, 1, W)
        B = [B; b]
    end
    dp = falses(H, W, 12601)
    for i = 1:H, j = 1:W
        difference = abs(A[i, j] - B[i, j])
        if i == 1 && j == 1
            dp[i, j, difference + 1] = true
            continue
        end
        if i == 1
            for k = 1:12601
                if dp[i, j - 1, k]
                    dp[i, j, k + difference] = true
                    dp[i, j, abs(k - 1 - difference) + 1] = true
                end
            end
            continue
        end
        if j == 1
            for k = 1:12601
                if dp[i - 1, j, k]
                    dp[i, j, k + difference] = true
                    dp[i, j, abs(k - 1 - difference) + 1] = true
                end
            end
            continue
        end

        for k = 1:12601
            if dp[i - 1, j, k] || dp[i, j - 1, k]
                dp[i, j, k + difference] = true
                dp[i, j, abs(k - 1 - difference) + 1] = true
            end
        end
    end
    ans = 0
    for i = 1:12601
        if dp[H, W, i]
            ans = i
            break
        end
    end
    println("$(ans - 1)")
end
solve()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function calc(dp::Array{Array{Bool,1},1},a::Array{Int,2},b::Array{Int,2},x::Int,y::Int,h::Int,w::Int,i::Int,base::Int)
	if dp[(x-1)*w+y][i]
		if y<w
			v1 = i+a[x,y+1]-b[x,y+1]
			if 1<=v1&&v1<=2*base+1
				dp[(x-1)*w+y+1][v1] = true
			end
			v2 = i-a[x,y+1]+b[x,y+1]
			if 1<=v2&&v2<=2*base+1
				dp[(x-1)*w+y+1][v2] = true
			end
		end
		if x<h
			v1 = i+a[x+1,y]-b[x+1,y]
			if 1<=v1&&v1<=2*base+1
				dp[x*w+y][v1] = true
			end
			v2 = i-a[x+1,y]+b[x+1,y]
			if 1<=v2&&v2<=2*base+1
				dp[x*w+y][v2] = true
			end
		end
	end
end

function main()
	h,w = readline() |> split |> parseMap
	a = zeros(Int,h,w)
	b = zeros(Int,h,w)
	ms = 0
	for i in 1:h
		a[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		b[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		for j in 1:w
			ms = max(ms,a[i,j]-b[i,j],b[i,j]-a[i,j])
		end
	end
	base = (h+w)*ms
	dp = [Bool[false for x in 1:2*base+1] for i in 1:h*w]
	dp[1][base+1+a[1,1]-b[1,1]] = true
	dp[1][base+1-a[1,1]+b[1,1]] = true

	z = base

	println(z)
end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	h,w = readline() |> split |> parseMap
	a = zeros(Int,h,w)
	b = zeros(Int,h,w)
	ms = 0
	for i in 1:h
		a[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		b[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		for j in 1:w
			ms = max(ms,abs(a[i,j]-b[i,j]))
		end
	end
	ms *=(h+w)
	dp = [Bool[false for x in 1:2*ms+1] for i in 1:h*w]
	dp[1][ms+1+a[1,1]-b[1,1]] = true
	dp[1][ms+1-a[1,1]+b[1,1]] = true
	for x in 1:h
		for y in 1:w
			for i in 1:2*ms+1
				if dp[(x-1)*w+y][i]
					if y<w
						v1 = i+a[x,y+1]-b[x,y+1]
						if 1<=v1&&v1<=2*ms+1
							dp[(x-1)*w+y+1][v1] = true
						end
						v2 = i-a[x,y+1]+b[x,y+1]
						if 1<=v2&&v2<=2*ms+1
							dp[(x-1)*w+y+1][v2] = true
						end
					end
					if x<h
						v1 = i+a[x+1,y]-b[x+1,y]
						if 1<=v1&&v1<=2*ms+1
							dp[x*w+y][v1] = true
						end
						v2 = i-a[x+1,y]+b[x+1,y]
						if 1<=v2&&v2<=2*ms+1
							dp[x*w+y][v2] = true
						end
					end
				end
			end
		end
	end
	z = ms
	for i in 1:2*ms+1
		if dp[h*w][i]
			z = min(z,abs(ms+1-i))
		end
	end
	println(z)
end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	h,w = readline() |> split |> parseMap
	a = zeros(Int,h,w)
	b = zeros(Int,h,w)
	for i in 1:h
		a[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		b[i,:] = readline() |> split |> parseMap
	end
	dp = [Array{Int,1}[zeros(Int,321) for i in 1:w] for i in 1:h]
	dp[1][1][161+a[1,1]-b[1,1]] = 1
	dp[1][1][161-a[1,1]+b[1,1]] = 1
	for x in 1:h
	for y in 1:w
		if y<w
			for i in 1:321
				if dp[x][y][i]==1
					if 1<=i+a[x,y+1]-b[x,y+1]<=321
						dp[x][y+1][i+a[x,y+1]-b[x,y+1]] = 1
					end
					if 1<=i-a[x,y+1]+b[x,y+1]<=321
						dp[x][y+1][i-a[x,y+1]+b[x,y+1]] = 1
					end
				end
			end
		end
		if x<h
			for i in 1:321
				if dp[x][y][i]==1
					if 1<=i+a[x+1,y]-b[x+1,y]<=321
						dp[x+1][y][i+a[x+1,y]-b[x+1,y]] = 1
					end
					if 1<=i-a[x+1,y]+b[x+1,y]<=321
						dp[x+1][y][i-a[x+1,y]+b[x+1,y]] = 1
					end
				end
			end
		end
	end
	end
	z = 80
	for i in 1:321
		if dp[h][w][i]==1
			z = min(z,abs(161-i))
		end
	end
	println(z)
end

main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	h,w = readline() |> split |> parseMap
	a = zeros(Int,h,w)
	b = zeros(Int,h,w)
	for i in 1:h
		a[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		b[i,:] = readline() |> split |> parseMap
	end
	dp = [[zeros(Int,321) for i in 1:w] for i in 1:h]
end
main()


parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	h,w = readline() |> split |> parseMap
	a = zeros(Int,h,w)
	b = zeros(Int,h,w)
	for i in 1:h
		a[i,:] = readline() |> split |> parseMap
	end
	for i in 1:h
		b[i,:] = readline() |> split |> parseMap
	end
	dp = [[zeros(Int,321) for i in 1:w] for i in 1:h]
	dp[1][1][161+a[1,1]-b[1,1]] = 1
	dp[1][1][161-a[1,1]+b[1,1]] = 1
	for co in 1:h
	for ro in 1:w
	x = co
	y = ro
		if y<w
				for i in 1:321
					if dp[x][y][i]==1
						if 1<=i+a[x,y+1]-b[x,y+1]<=321
							dp[x][y+1][i+a[x,y+1]-b[x,y+1]] = 1
						end
						if 1<=i-a[x,y+1]+b[x,y+1]<=321
							dp[x][y+1][i-a[x,y+1]+b[x,y+1]] = 1
						end
					end
				end
		end
		if x<h
				for i in 1:321
					if dp[x][y][i]==1
						if 1<=i+a[x+1,y]-b[x+1,y]<=321
							dp[x+1][y][i+a[x+1,y]-b[x+1,y]] = 1
						end
						if 1<=i-a[x+1,y]+b[x+1,y]<=321
							dp[x+1][y][i-a[x+1,y]+b[x+1,y]] = 1
						end
					end
				end
			end
	end
	end
	z = 80
	for i in 1:321
		if dp[h][w][i]==1
			z = min(z,abs(161-i))
		end
	end
	println(z)
end

main()


function f(kv)
	pre=-10^18
	ret=0
	for (l,r)=kv
		ret+=max(0,r-max(pre,l-1))
		pre=max(pre,r)
	end
	ret
end
function main()
	N,X,D=map(x->parse(Int,x),split(readline()))
	if D==0
		println(X==0 ? 1 : N+1)
		exit()
	end
	if D<0
		D=-D
		X=-X
	end
	S=Dict{Int,Array{Pair{Int,Int}}}()
	for k=0:N
		L=fld(k*X,D)
		U=L+div(k*(k-1),2)=>L+N*k-div(k*(k+1),2)
		x=get(S,mod(k*X,D),Pair{Int,Int}[])
		push!(x,U)
		S[mod(k*X,D)]=x
	end
	ans=0
	for (_,a)=S
		ans+=f(sort(a))
	end
	println(ans)
end
main()

Score : 600 points

Problem Statement

We have an integer sequence A of length N, where A_1 = X, A_{i+1} = A_i + D (1 \leq i < N ) holds.

Takahashi will take some (possibly all or none) of the elements in this sequence, and Aoki will take all of the others.

Let S and T be the sum of the numbers taken by Takahashi and Aoki, respectively. How many possible values of S - T are there?

Constraints

-10^8 \leq X, D \leq 10^8

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X D

Output

Print the number of possible values of S - T.

Sample Input 1

3 4 2

Sample Output 1

8

A is (4, 6, 8).

There are eight ways for (Takahashi, Aoki) to take the elements: ((), (4, 6, 8)), ((4), (6, 8)), ((6), (4, 8)), ((8), (4, 6))), ((4, 6), (8))), ((4, 8), (6))), ((6, 8), (4))), and ((4, 6, 8), ()).

The values of S - T in these ways are -18, -10, -6, -2, 2, 6, 10, and 18, respectively, so there are eight possible values of S - T.

Sample Input 2

2 3 -3

Sample Output 2

2

A is (3, 0). There are two possible values of S - T: -3 and 3.

Sample Input 3

100 14 20

Sample Output 3

49805


function main()
	N,X,D=map(x->parse(Int,x),split(readline()))
	if D==0
		println(X==0 ? 1 : N+1)
		exit()
	end
	if D<0
		D=-D
		X=-X
	end
	S=Dict{Int,Array{Pair{Int,Int}}}()
	for k=0:N
		L=fld(k*X,D)
		U=L+div(k*(k-1),2)=>L+N*k-div(k*(k+1),2)
		x=get(S,mod(k*X,D),Pair{Int,Int}[])
		push!(x,U)
		S[mod(k*X,D)]=x
	end
	ans=0
	for (_,a)=S
		pre=-10^18
		for (l,r)=sort(a)
			ans+=max(0,r-max(pre,l)+1)
			pre=max(pre,r+1)
		end
	end
	println(ans)
end
main()


function main()
	N,X,D=map(x->parse(Int,x),split(readline()))
	if D==0
		println(X==0 ? 1 : N+1)
		exit()
	end
	if D<0
		D=-D
		X=-X
	end
	S=Dict{Int,Array{Pair{Int,Int}}}()
	for k=0:N
		L=fld(k*X,D)
		U=L+div(k*(k-1),2)=>L+N*k-div(k*(k+1),2)
		x=get(S,k*X%D,Pair{Int,Int}[])
		push!(x,U)
		S[k*X%D]=x
	end
	ans=0
	for (_,a)=S
		pre=-10^18
		for (l,r)=sort(a)
			ans+=r-max(pre,l)+1
			pre=r+1
		end
	end
	println(ans)
end
main()