Problem:


Score : 500 points

Problem Statement

In CODE FESTIVAL XXXX, there are N+1 participants from all over the world, including Takahashi.

Takahashi checked and found that the time gap (defined below) between the local times in his city and the i-th person's city was D_i hours.
The time gap between two cities is defined as follows. For two cities A and B, if the local time in city B is d o'clock at the moment when the local time in city A is 0 o'clock, then the time gap between these two cities is defined to be min(d,24-d) hours.
Here, we are using 24-hour notation.
That is, the local time in the i-th person's city is either d o'clock or 24-d o'clock at the moment when the local time in Takahashi's city is 0 o'clock, for example.

Then, for each pair of two people chosen from the N+1 people, he wrote out the time gap between their cities. Let the smallest time gap among them be s hours.

Find the maximum possible value of s.

Constraints

1 \leq N \leq 50

0 \leq D_i \leq 12

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N

Output

Print the maximum possible value of s.

Sample Input 1

3
7 12 8

Sample Output 1

4

For example, consider the situation where it is 7, 12 and 16 o'clock in each person's city at the moment when it is 0 o'clock in Takahashi's city. In this case, the time gap between the second and third persons' cities is 4 hours.

Sample Input 2

2
11 11

Sample Output 2

2

Sample Input 3

1
0

Sample Output 3

0

Note that Takahashi himself is also a participant.



Sample input:
3
7 12 8


Sample output:
4

Submission status: Accepted

Solution code:
def inpl(): return [int(i) for i in input().split()]
import sys
N = int(input())

D = inpl()
tt = [0 for _ in range(24)]
tt[0] = 2
for d in D:
    tt[d] += 1
    tt[-d] += 1    

for t in tt:
    if t > 2:
        print(0)
        sys.exit()
if N > 11:
    prev = tt[-1]
    for t in tt:
        if t == 0:
            prev = 0
            continue
        if t == 1:
            if prev == 2:
                print(1)
                break
            prev = 1
        if t == 2:
            if prev == 1 or prev == 2:
                print(1)
                break
            prev = 2
    else:
        print(2)
    sys.exit()
ans = 0
for i in range(2**N):
    stri = format(i, 'b')
    stri = '0'*(N-len(stri)) +stri
    tt = [0 for _ in range(24)]
    tt[0] = 1
    for j in range(N):
        c = 1
        if stri[j] == '0':
             c = -1
        tt[c * D[j]] += 1
    for t in tt:
        if t > 1:
            break
    else:
        ctr = 1
        H = []
        for i in range(48):
            if tt[i%24] == 0:
                ctr += 1
            else:
                H.append(ctr)
                ctr = 1
        H.pop(0)
        ans = max(ans, min(H))
print(ans)

Submission status: Accepted

Solution code:
from numpy import *
from scipy import *

n = array(input(), dtype=int)
d = array(input().split(), dtype=int)
h = zeros(24, dtype=int)
h[0] = 1

for x in d:
    h[x] += 1
ans = array(0, dtype=int)
if h[0] >= 2 or h[12] >= 2:
    print(ans)
    exit()
for x in h:
    if x >= 3:
        print(ans)
        exit()

for i in range(12):
    if h[i] >= 2:
        h[24-i] = 2

def dfs(depth, h):
    global ans
    r = 0
    res = inf
    for i in range(1,24):
        r += 1
        if h[i] != 0:
            res = min(res,r)
            r = 0
    res = min(res,r+1)
    ans = max(ans,res)
    if depth == 12:
        return
    if h[depth] == 1:
        h[depth], h[24-depth] = h[24-depth], h[depth]
        dfs(depth+1, h)
        h[depth], h[24-depth] = h[24-depth], h[depth]
    dfs(depth+1, h)

dfs(1, h)
print(ans)

Submission status: Accepted

Solution code:
def solve(N, D):
    fill = [0] * 24
    fill[0] = 1

    left = False
    for i in range(N):
        if D[i] == 0:
            print(0)
            return 0
        elif D[i] == 12:
            if fill[12] == 1:
                print(0)
                return 0
            else:
                fill[12] = 1
        else:
            if not left:
                if fill[D[i]] == 0:
                    fill[D[i]] = 1
                    left = True
                elif fill[24-D[i]] == 0:
                    fill[24-D[i]] = 1
                    left = False
                else:
                    print(0)
                    return 0
            else:
                if fill[24-D[i]] == 0:
                    fill[24-D[i]] = 1
                    left = False
                elif fill[D[i]] == 0:
                    fill[D[i]] = 1
                    left = True
                else:
                    print(0)
                    return 0

    s = 24
    cnt = 0
    for i in range(1, 24):
        if i == 23:
            if fill[i] == 0:
                cnt += 1
                s = min(s, cnt + 1)
            else:
                s = min(s, cnt + 1)
        else:
            if fill[i] == 0:
                cnt += 1
            else:
                s = min(s, cnt + 1)
                cnt = 0
    print(s)

if __name__ == '__main__':
    N = int(input())
    D = list(map(int, input().split()))
    solve(N, sorted(D))

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n = I()
    a = sorted(LI())
    i = 0
    b = [0]
    for c,i in zip(a,range(n)):
        if i % 2 == 0:
            b.append(c)
        else:
            b.append(24-c)
    b.sort()
    r = a[0]
    for i in range(n):
        if b[i+1] - b[i] < r:
            r = b[i+1] - b[i]

    return r



print(main())

Submission status: Accepted

Solution code:
n=input()
a=sorted(map(int,raw_input().split()))
r=0
b=[0]+[a[j]*(-1)**j%24 for j in range(n)]
s=24
for j in range(n):
 for k in range(j+1,n+1):s=min(s,(b[j]-b[k])%24,(b[k]-b[j])%24)
r=max(r,s)
print r

Submission status: Accepted

Solution code:
N = int(input())
D = [int(x) for x in input().split()]
D.append(0)
D.sort()
ans = []
for i in range(N + 1):
    if i % 2 == 0:
        ans.append(D[i])
    else:
        ans.append((24 - D[i]) % 24)
ans.sort()
print(min(min(ans[i + 1] - ans[i] for i in range(N)), 24 - ans[-1]))

Submission status: Accepted

Solution code:
from collections import Counter


def solve(n, ds):
    if n >= 24:
        return 0
    freq = Counter(ds)
    if (0 in freq) or (freq[12] >= 2) or max(freq.values()) >= 3:
        return 0
    up_low = [0, 0]
    switch = 0
    ans = 25
    for d, s in sorted(freq.items()):
        if s == 2:
            ans = min(ans, d - up_low[0], d - up_low[1])
            up_low[0] = up_low[1] = d
        else:
            ans = min(ans, d - up_low[switch])
            up_low[switch] = d
            switch ^= 1
    ans = min(ans, 24 - sum(up_low))
    return ans


print(solve(int(input()), list(map(int, input().split()))))

Submission status: Accepted

Solution code:
from collections import Counter
import sys

N = int(input())
ds = list(map(int,input().split()))
ctr = Counter(ds)
if 0 in ctr:
    print(0)
    sys.exit()

hs = (1 << 24) + 1
undef = []
for d,c in ctr.items():
    if c > 2:
        print(0)
        sys.exit()
    elif c == 2:
        hs |= (1 << d)
        hs |= (1 << (24-d))
    else: #c == 1
        undef.append(d)

ans = 0
for i in range(2**len(undef)):
    _hs = hs
    for j,u in enumerate(undef):
        if (i >> j) & 1:
            _hs |= (1 << u)
        else:
            _hs |= (1 << (24-u))
    min_interval = 24
    prev = 0
    for k in range(1,25):
        if (_hs >> k) & 1 == 0: continue
        min_interval = min(min_interval, k - prev)
        prev = k
    ans = max(ans, min_interval)
print(ans)

Submission status: Accepted

Solution code:
import sys
N = int(input())
D = [int(d) for d in input().split()]
# N = 5
# D = [3, 5, 7, 9, 12]
counts = [0] * 13

if 0 in D or D.count(12) > 1:
    print(0)
    sys.exit()

for i in range(N):
    if D[i] > 12:
        D[i] = 24 - D[i]
D.append(0)

for d in D:
    counts[d] += 1

E = []
F = []
for idx, count in enumerate(counts):
    if count > 2:
        print(0)
        sys.exit()
    elif count == 2:
        E.append(idx)
        E.append(24 - idx)
    elif idx == 0 or (idx == 12 and count > 0):
        E.append(idx)
    elif count == 1:
        F.append(idx)

max_val = 0


def update(arr):
    global max_val
    min_val = 24
    arr.sort()
    for i in range(1, len(arr)):
        if arr[i] - arr[i - 1] < min_val:
            min_val = arr[i] - arr[i - 1]
    if 24 - arr[-1] < min_val:
        min_val = 24 - arr[-1]
    if min_val > max_val:
        max_val = min_val

for i in range(2 ** len(F)):
    G = [0] * len(F)
    for j in range(len(F)):
        if i & (2 ** j):
            G[j] = 24 - F[j]
        else:
            G[j] = F[j]
    update(E + G)

print(max_val)

Submission status: Accepted

Solution code:
import sys

N = int(sys.stdin.readline().strip())
D = [0] + [int(x) for x in sys.stdin.readline().strip().split()]

def kei(xs, n):
    xs = xs + [x + 24 for x in xs]
    m1 = min(abs(n - x) for x in xs)
    m2 = min(abs((24 - n) - x) for x in xs)
    if m1 >= m2:
        return n, m1
    else:
        return 24 - n, m2

def calc(D):
    D.sort()
    #print(D)
    n = len(D)
    if N > 24:
        return 0
    if D[1] == 0:
        return 0
    xs = D[:2]
    D = D[2:]
    r = xs[1] - xs[0]
    for d in D:
        #print(xs, d)
        c, m = kei(xs, d)
        #print("r", c, m)
        if m < r:
            r = m
        xs += [c]
    return r



print(calc(D))

Submission status: Accepted

Solution code:
N = int(input())
D = list(map(int,input().split(" ")))

ans = D[:]
D.sort()
D_1 = []
D_2 = []

for i in range(N):
	if i % 2 == 0:
		D_1.append(24-D[i])
		D_2.append(D[i])
	else:
		D_2.append(24-D[i])
		D_1.append(D[i])


for i in range(N):
	for j in range(i+1,N):
		df1 = abs(D_1[j] - D_1[i])
		df2 = abs(D_2[j] - D_2[i])
		
		df1 = min([df1,24-df1])
		df2 = min([df2,24-df2])
			
		ans.append(df1)
		ans.append(df2)

print(min(ans))

Submission status: Accepted

Solution code:
from collections import Counter
import itertools

N = int(input())
Ds = list(map(int, input().split())) + [0]

cnt = Counter(Ds)

if max(cnt.values()) >= 3:
    print(0)
    exit()

citys = []
rest = []
for k, v in cnt.items():
    if v == 2:
        if k == 0 or k == 12:
            print(0)
            exit()
        citys.append(k)
        citys.append(24 -k)
    else:
        rest.append(k)


def check(citys):
    if len(citys) <= 1:
        return 24

    citys.sort()

    ans = 24
    prev = citys[-1] - 24
    for c in citys:
        ans = min(ans, c - prev)
        prev = c

    return ans


if check(citys) == 1:
    print(1)
    exit()

ans = 0
for ops in itertools.product('+-', repeat=len(rest)):
    citys2 = citys.copy()
    for i in range(len(rest)):
        if ops[i] == '+':
            citys2.append(rest[i])
        else:
            citys2.append(24 - rest[i])

    ans = max(ans, check(citys2))

print(ans)

Submission status: Accepted

Solution code:
def timdiff(dif):
    l=[]
    for i in range(24):
        if dif[i]==1:
            l+=[i]
        if dif[i]>=2:
            return 0
    m=24
    for i in range(len(l)):
        if i < len(l)-1:
            m=min(m,l[i+1]-l[i])
    if len(l)>=2:
        m=min(m,24-l[len(l)-1])
    return m

n=int(input())
d=list(map(int,input().split(' ')))
diff=[0]*24
if n>=24:
    print(0)
elif n<12: #global search
    m=0
    for i in range(2**n):
        for j in range(1,24):
            diff[j]=0
        diff[0]=1
        for j in range(n):
            if (i >> j)%2==1:
                diff[d[j]]+=1
            elif d[j]==0:
                diff[0]+=1
            else:
                diff[24-d[j]]+=1
        m=max(m,timdiff(diff))
    print(m)
else: #judge 0 or 1
    bl=False
    for i in range(13):
        if bl:
            break
        m=0
        for j in range(n):
            if d[j] == i:
                m+=1
            if m>2 or (i==0 and d[j]==0) or (i==12 and m>=2):
                bl=True
                break
        
    if bl:
        print(0)
    else:
        print(1)

Submission status: Accepted

Solution code:
# coding: utf-8

import itertools
import collections


def main():
    n = int(input())
    c = collections.Counter(map(int, input().split()))
    if c[0] > 0:
        return 0
    if c.most_common(1)[0][1] >= 3:
        return 0
    l1 = []
    l2 = []
    for i, cnt in c.most_common():
        if cnt == 2:
            l2.append(i)
        elif cnt == 1:
            l1.append(i)
    s = 0
    for i in range(len(l1) + 1):
        for invs in itertools.combinations(l1, i):
            l = [0]
            for k in l1:
                l.append(-k if k in invs else k)
            for k in l2:
                l.append(k)
                l.append(-k)
            l.sort()
            ss = 24
            for j in range(len(l)-1):
                ss = min(l[j + 1] - l[j], ss)
            d = l[-1] - l[0]
            ss = min(min(d, 24-d), ss)
            s = max(s, ss)

    return s

print(main())

Submission status: Accepted

Solution code:
from collections import Counter
N = int(input())
ds = list(map(int, input().split()))
c = Counter(ds)
cs = c.most_common()

if N >= 24 or cs[0][1] >= 3 or 0 in c:
  print("0")
  exit()

l = len(cs)
k = 0
s = (1 << 0) + (1 << 24)
while k < l and cs[k][1] == 2:
  s += (1 << cs[k][0]) + (1 << (24 - cs[k][0]))
  k += 1

def process(s, i):
  if i == l:
    return min(map(len, bin(s)[2:].split("1")[1:-1])) + 1
  return max(
    process(s + (1 << cs[i][0]), i+1),
    process(s + (1 << (24 - cs[i][0])), i+1),
  )

print(process(s, k))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
D = list(map(int,input().split()))

C = [0] * 13
C[0] = 1
for i in range(n):
    C[D[i]] += 1

if C[0] >= 2 or C[12] >=2:
    print(0)
    sys.exit()

for i in range(n):
    if C[i] >= 3:
        print(0)
        sys.exit()

D = []
for i in range(13):
    for j in range(C[i]):
        D.append(i)
n = len(D)
A = [0] * n
ans0 = 0
for i in range(2**n):
    ib = format(i, "b").zfill(n)
    for j in range(n):
        A[j] = D[j] * (-1) ** int(ib[j])
    ans = 30
    for j in range(n):
        for k in range(j+1, n):
            di = abs(A[k] - A[j])
            # print(ans)
            ans = min(ans, min(di, 24-di))
    # print(ib, ans0,ans)
    ans0 = max(ans0, ans)
print(ans0)

Submission status: Runtime Error

Solution code:
#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main(){
	int n;
	cin >> n;
	vector<int> c(25);
	c[0] = 1;
	for(int i = 0; i < n; i++){
		int x;
		cin >> x;
		c[x]++;
	}
	c[24] = c[0];
	int p = 0;
	for(int i = 1; i <= 11; i++){
		if(c[i] >= 1){
			c[24 - i] = (c[i] + 1 - p) / 2;
			c[i] = (c[i] + p) / 2;
			p = 1 - p;
		}
	}
	int t = 1, ans = 24;
	for(int i = 1; i <= 24; i++){
		if(c[i] >= 2){
			ans = 0;
			break;
		}else if(c[i] == 1){
			ans = min(ans, t);
			t = 1;
		}else{
			t++;
		}
	}
	cout << ans << endl;
	return 0;
}

Submission status: Runtime Error

Solution code:
from collections import Counter
from itertools import product, combinations


def solve(n, ds):
    if n >= 24:
        return 0
    freq = Counter(ds)
    if 0 in freq or freq[12] >= 2 or max(freq.values()) >= 3:
        return 0
    cmp = set()
    alt = []
    for d, l in freq.items():
        if l == 2 or d == 12:
            cmp.add(d)
            cmp.add(24 - d)
        else:
            alt.append((d, 24 - d))
    ans = min((abs(x - y) for x, y in combinations(cmp, 2)), default=0)
    for prd in product((0, 1), repeat=len(alt)):
        tmp_cmp = cmp.copy().union(x[i] for x, i in zip(alt, prd))
        tmp = min(abs(x - y) for x, y in combinations(tmp_cmp, 2))
        tmp = min(tmp, min(freq.keys()))
        ans = max(ans, tmp)
    return ans


print(solve(int(input()), list(map(int, input().split()))))

Submission status: Runtime Error

Solution code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
	int i, j;
	int n;
	int d[50];
	scanf("%d", &n);
	for (i = 0; i < n; i++)
		scanf("%d", &d[i]);

	int check;
	//	if check>0 => back is larger
	int nearest12[2] = { d[0],d[1] };
	if (d[0] > d[1])
		check = -1;
	else
		check = 1;

	for (i = 2; i < n; i++)
	{
		if (check==1)
		{
			if (12 - nearest12[1] > 12 - d[i])
				nearest12[1] = d[i];
		}
		else
		{
			if (12 - nearest12[0] > 12 - d[i])
				nearest12[0] = d[i];
		}
		if (nearest12[0] > nearest12[1])
			check = -1;
		else
			check = 1;
	}
	printf("%d", abs((24 - nearest12[0]) - nearest12[1]));
	return 0;
}

Submission status: Runtime Error

Solution code:
# -*- coding:utf-8 -*-
import sys

DBG_FLAG = 0

def p_dbg(str):
    if(DBG_FLAG == 1):
        sys.stdout.flush()
        print str

# 高橋君の都市とa,bの時差が
# (1) 12を超えないとき（例えば、2時間、4時間）⇒加算。
# (1) 12を超えるとき　（例えば、6時間、8時間）⇒減算して絶対値
def cal_diff(diff_a, diff_b):
    diff_a_24 = 24 - diff_a
    diff_b_24 = 24 - diff_b
    p_dbg("diff:"+str(diff_a)+","+str(diff_b))
    p_dbg(diff_a - diff_b)
    p_dbg(diff_b - diff_a),
    p_dbg(diff_a_24 - diff_b_24)
    p_dbg(diff_b_24 - diff_a_24)
    p_dbg(diff_a - diff_b_24)
    p_dbg(diff_b_24 - diff_a)
    p_dbg(diff_a_24 - diff_b)
    p_dbg(diff_b - diff_a_24)
    return max((diff_a - diff_b), (diff_b - diff_a),
               (diff_a_24 - diff_b_24), (diff_b_24 - diff_a_24),
               (diff_a - diff_b_24), (diff_b_24 - diff_a),
               (diff_a_24 - diff_b), (diff_b - diff_a_24))

city_num = int(raw_input())
diff_array = map(int, raw_input().split())
p_dbg(diff_array)

array = [[]]
min_diff = cal_diff(diff_array[0],diff_array[1])

for i in range(len(diff_array)):
    for j in range(len(diff_array)):
        if i == j:
            pass
        else:
            tmp_diff = cal_diff(diff_array[i],diff_array[j])
            p_dbg("tmp:"+str(tmp_diff)+":"+str(i)+","+str(j))
            if tmp_diff < min_diff:
                min_diff = tmp_diff

print min_diff

Submission status: Runtime Error

Solution code:
s = input()
n = {'a': 0, 'b': 0, 'c': 0}
for c in s:
    n[c] += 1

import sys
if len(s) == 1:
    print('YES')
    sys.exit(0)

min = int(len(s)/3)
val = list(n.values())
val.sort()
if len(s)%3 == 0:
    if val == [min, min, min]:
        print('YES')
    else:
        print('NO')
elif len(s)%3 == 1:
    if val == [min, min, min+1]:
        print('YES')
    else:
        print('NO')
elif len(s)%3 == 2:
    if val == [min, min+1, min+1]:
        print('YES')
    else:
        print('NO')

Submission status: Runtime Error

Solution code:
N = int(input())
D = list(map(int,input().split(" ")))

ans = D[:]


D.sort()

for i in range(N):
	if i % 2 == 0:
		D_1.append(24-D[i])
		D_2.appned(D[i])
	else:
		D_2.append(24-D[i])
		D_1.appned(D[i])


for i in range(N):
	for j in range(i+1,N):
		df1 = abs(D_1[j] - D_1[i])
		df2 = abs(D_2[j] - D_2[i])
		
		df1 = min([df1,24-df1])
		df2 = min([df2,24-df2])
			
		ans.append(df1)
		ans.append(df2)

print(min(df1))