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:
N = int(input())
D = list(map(int, input().split()))
map_D = dict()
map_D[0] = 1
for d in D:
    if d in map_D:
        map_D[d] += 1
    else:
        map_D[d] = 1

new_D = []
is_zero = False
for (k, v) in map_D.items():
    
    if ((k == 0 or k == 12) and v >= 2) and v >= 3:
        is_zero = True
        break
    else:
        for i in range(v):
            new_D.append(k)

new_D.sort()
final_D = []
for i in range(len(new_D)):
    if i % 2 == 0:
        final_D.append(new_D[i])
    else:
        final_D.append(24 - new_D[i])

ans = 100
for i in range(len(final_D) - 1):
    for j in range(i + 1, len(final_D)):
        ans = min(ans, min(24 - abs(final_D[i] - final_D[j]), abs(final_D[i] - final_D[j])))

if is_zero:
    print(0)
else:
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())
d = list(map(int, input().split()))
d.append(0)
d.sort()

deq = deque()

for i in range(n + 1):
    if i & 1:
        deq.append(d[i])
    else:
        deq.appendleft(-d[i])

ans = abs(deq[0] + 24 - deq[n])
for i in range(n):
    ans = min(ans, deq[i + 1] - deq[i])

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
D=[0]+list(map(int,input().split()))
D.sort()
for i in range(1,N+1):
  if i&1:
    D[i]=(24-D[i])%24
D.sort()
P=24-D[N]
for i in range(N):
  P=min(P,D[i+1]-D[i])
print(P)

Submission status: Accepted

Solution code:
n = int(input())
arr = list(map(int,input().split()))

arr.sort()

pep = [0 for i in range(24)]
pep[0] = 1

lr =True
for a in arr:
    if a== 0:
        pep[0] += 1
    else:
        if pep[a] > 1:
            pep[24-a] += 1
        elif pep[24-a] > 1:
            pep[a] += 1
        else:
            if lr:
                pep[a] += 1
                lr = not lr
            else:
                pep[24-a] += 1
                lr = not lr

ans = 1e9
for i in range(24):
    if pep[i] > 1:
        ans = 0
        break
    for j in range(i+1,24):
        if pep[i] > 0 and pep[j] > 0:
            d = min(j-i,24-(j-i))
            if ans > d:
                ans = d
# print(pep)
print(ans)

Submission status: Accepted

Solution code:
import sys
from itertools import product
from copy import deepcopy

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n = int(input())
    D = list(map(int, input().split()))

    cnt = [0] * 13
    cnt[0] = 1
    for d in D:
        cnt[d] += 1

    P = []
    init_T = []
    for i in range(13):
        if i == 0 or i == 12:
            if cnt[i]:
                if cnt[i] == 1:
                    init_T.append(i)
                else:
                    print(0)
                    exit()
        else:
            if cnt[i]:
                if cnt[i] == 1:
                    P.append(i)
                elif cnt[i] == 2:
                    init_T.append(i)
                    init_T.append(24 - i)
                else:
                    print(0)
                    exit()

    res = 0
    for pattern in product([0, 1], repeat=len(P)):
        T = deepcopy(init_T)
        for idx, p in enumerate(pattern):
            if p == 0:
                T.append(P[idx])
            else:
                T.append(24 - P[idx])

        min_gap = f_inf
        for i in range(len(T)):
            for j in range(i + 1, len(T)):
                gap = abs(T[i] - T[j])
                min_gap = min(min_gap, min(gap, 24 - gap))

        res = max(res, min_gap)

    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
# CODE FESTIVAL 2017 Final
# C - Time Gap
# https://atcoder.jp/contests/cf17-final/tasks/cf17_final_c
from collections import Counter
N = int(input())
*A, = map(int, input().split())

INF = 1 << 30
C = Counter(A)
if N >= 24 or 0 in C:
    print(0)
    exit()

dt = []
nt = []
for k, v in C.items():
    if v > 2:
        print(0)
        exit()
    if v == 2:
        dt.append(k)
        dt.append(24-k)
    if v == 1:
        nt.append(k)

tmp = min(A)
for i, t in enumerate(dt):
    for s in dt[i+1:]:
        if abs(t-s) < tmp:
            tmp = abs(t-s)
ans = 0

M = len(nt)
if M:
    for bit in range(1 << M):
        D = [0]*M
        for i in range(M):
            if bit >> i & 1:
                D[i] = nt[i]
            else:
                D[i] = 24-nt[i]

        mn = tmp
        for j, d in enumerate(D):
            for e in D[j+1:]:
                if abs(d-e) < mn:
                    mn = abs(d-e)
            for t in dt:
                if abs(d-t) < mn:
                    mn = abs(d-t)

        if mn != INF and mn > ans:
            ans = mn
else:
    ans = tmp

print(ans)

Submission status: Accepted

Solution code:
def dist(a,b):
    return min(abs(a-b),24-abs(a-b))
from itertools import groupby, accumulate, product, permutations, combinations
from copy import copy
def solve():
    N = int(input())
    D = list(map(int, input().split()))
    c = [0]*13
    for i in range(N):
        c[D[i]]+=1
    choices = []
    dicided = [0]
    if c[12]>1:
        return 0
    if c[12]==1:
        dicided.append(12)
    if c[0]>0:
        return 0
    for i in range(1,12):
        if c[i]>2:
            return 0
        if c[i]==1:
            choices.append([i,24-i])
        if c[i]==2:
            dicided.append(i)
            dicided.append(24-i)
    ans = 0
    for p in product([0,1],repeat=len(choices)):
        lis = copy(dicided)
        for i in range(len(choices)):
            lis.append(choices[i][p[i]])
        m = 24
        for i in range(len(lis)):
            for j in range(len(lis)):
                if i!=j:
                    m = min(m,dist(lis[i],lis[j]))
        ans = max(ans,m)
    return ans
print(solve())

Submission status: Accepted

Solution code:
N = int(input())
D = sorted(list(map(int,input().split())))
for i in range(0,N,2):
    D[i] = 24-D[i]
D.insert(0,0)
dmin = 24
for i in range(N):
    for j in range(i+1,N+1):
        a = D[i]
        b = D[j]
        if a>b:
            a,b = b,a
        d = b-a
        if d>12:
            d = 24-d
        dmin = min(dmin,d)
print(dmin)

Submission status: Accepted

Solution code:
from collections import *

N = int(input())
D = list(map(int, input().split()))
cnt = Counter(D)
l = []
T = [0]

for k, v in cnt.items():
    if v>=3:
        print(0)
        exit()
    
    if v==1:
        l.append(k)
    else:
        T.append(k)
        T.append(24-k)

ans = 0

for i in range(1<<len(l)):
    t = T[:]
    
    for j in range(len(l)):
        if (i>>j)&1:
            t.append(l[j])
        else:
            t.append(24-l[j])
    
    t.sort()
    d = t[0]+24-t[-1]
    ans_cand = min(d, 24-d)
    
    for i in range(len(t)-1):
        d = t[i+1]-t[i]
        ans_cand = min(ans_cand, min(d, 24-d))
    
    ans = max(ans, ans_cand)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
D = list(map(int, input().split()))
from collections import Counter
C = Counter(D)
#print(C)

A = [0]
C = list(C.items())
C.sort()
#print(C)
for i in range(len(C)):
    k, v = C[i]
    if k != 0 and k != 12:
        if v == 1:
            A.append(k*(-1)**i)
        elif v == 2:
            A.append(k)
            A.append(-k)
        else:
            print(0)
            exit()
    else:
        if v == 1:
            A.append(k*(-1)**i)
        else:
            print(0)
            exit()

#print(A)
m = len(A)
ans = 10**18
for i in range(m-1):
    for j in range(i+1, m):
        temp = min(abs(A[i]-A[j]), 24-abs(A[i]-A[j]))
        ans = min(ans, temp)
print(ans)

Submission status: Accepted

Solution code:
import collections
import itertools

def dfs(used:set, newi:int, i:int):
    global D, N, iters
    new1 = newi
    new2 = (24-newi) * (newi!=0)
    if new1 not in used:
        used.add(new1)
        if i+1 == N:
            iters.append(list(used))
        else:
            dfs(used, D[i+1], i+1)
        used.remove(new1)
    if new2 not in used:
        used.add(new2)
        if i+1 == N:
            iters.append(list(used))
        else:
            dfs(used, D[i+1], i+1)
        used.remove(new2)

def main():
    global D, N, iters
    N = int(input())
    D = list(map(int, input().split()))
    D.sort()
    iters = []
    used = set([0])
    dfs(used, D[0], 0)
    if len(iters) == 0:
        print(0)
        return
    maxd = 0
    for tmp in iters:
        pairs = itertools.combinations(tmp, 2)
        mind = 25
        for x, y in pairs:
            mind = min(mind, min(abs(x-y), 24-abs(x-y)))
        maxd = max(maxd, mind)
    print(maxd)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import collections
n=int(input())
s=list(map(int,input().split()))
if 0 in s:
  print(0)
  quit()
s=collections.Counter(s)
l1=[0]
l2=[]
for x in s:
  if s[x]>2:
    print(0)
    quit()
  elif s[x]>1:
    l2.append(x)
    l2.append(24-x)
  else:
    l1.append(x)
x=len(l1)
an=0
for i in range(2**x):
  memo=[0]*x
  for j in range(x):
    if ((i >> j) & 1):
      memo[j]=l1[j]
    else:
      memo[j]=24-l1[j] 
  ans=12
  memo=memo+l2
  for k in range(len(memo)):
    for m in range(k+1,len(memo)):
      ans=min(ans,min(abs(memo[k]-memo[m]),24-abs(memo[k]-memo[m])))
  an=max(ans,an)
print(an)

Submission status: Accepted

Solution code:
n = int(input())
d = list(map(int, input().split()))
d.sort()
d_a = [v if i % 2 == 0 else 24-v for i, v in enumerate(d)]
d_b = [v if i % 2 == 1 else 24-v for i, v in enumerate(d)]
d_a.append(0)
d_b.append(0)
d_a.sort()
d_b.sort()
res_a = 24
res_b = 24
for i in range(n):
    res_a = min(res_a, d_a[i+1]-d_a[i])
    res_b = min(res_b, d_b[i+1]-d_b[i])
res_a = min(res_a, 24-d_a[-1]+d_a[0])
res_b = min(res_a, 24-d_b[-1]+d_b[0])
res = max(res_a, res_b)
if res == 24:
    res = 0
print(res)

Submission status: Accepted

Solution code:
n = int(input())
d = [int(i) for i in input().split()]
x = [0] * 13
for i in d:
    x[i] += 1
x[0] += 1

if max(x) > 2:
    print(0)
    exit()
ans = 0
for i in range(1 << 13):
    a = []
    for j in range(13):
        if x[j]==1:
            if (i >> j) & 1 == 1:
                a.append(j)
            else:
                a.append(24 - j)
        elif x[j] == 2:
            a.append(j)
            a.append(24 - j)
    aa = 10**18
    for j in range(len(a)):
        for k in range(j + 1, len(a)):
            d = abs(a[j] - a[k])
            aa = min(aa, min(d, 24-d))
    ans = max(ans, aa)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ds = list(map(int, input().split()))

from collections import defaultdict
d = defaultdict(int)

d[0] += 1
for d_ in ds:
    d[d_] += 1
    if (d_ == 12 or d_ == 0) and d[d_] == 2:
        print(0)
        exit()
    elif d[d_] == 3:
        print(0)
        exit()

def calcmin(tmp):
    n = len(tmp)
    ret = 1 << 50
    for i in range(n):
        for j in range(i+1,n):
            ret = min(ret, abs(tmp[i]-tmp[j]),24-abs(tmp[i]-tmp[j]))
    return ret

two = []
x = []

for k in d.keys():
    if d[k] == 2 or k == 12:
        two.append(k)
        two.append(24-k)
    elif d[k] == 1:
        x.append(k)

two = list(set(two))
n = len(x)
ans = 0
for i in range(1 << n):
    tmp = x[:]
    for j in range(n):
        if i & (1 << j):
            tmp[j] = 24-x[j]
    # print(tmp,two)
    tmp.extend(two)
    ans = max(calcmin(tmp), ans)

print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode('utf-8')

#import numpy as np
from itertools import combinations

def main():
	n=II()
	d=LI()
	d.sort()
	t=[0]*25
	t[0]=1
	t[24]=1

	for i in range(n):
		if i%2==0:
			t[d[i]]+=1
		else:
			t[24-d[i]]+=1

	if max(t)>=2:
		print(0)
		exit(0)

	ans=12
	cnt=0
	for i in range(1,25):
		if t[i]==0:
			cnt+=1
		else:
			ans=min(ans,cnt+1)
			cnt=0

	print(ans)


if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
n=int(input())
d=list(map(int,input().split()))
d.sort()
t=[0,24]
for i in range(n):
  if i%2==1:t.append(d[i])
  else:t.append((24-d[i])%24)
t.sort()
print(min(t[i]-t[i-1]for i in range(1,len(t))))

Submission status: Accepted

Solution code:
import math
#import sys
#input = sys.stdin.readline

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ZipArray(a):
    aa = [[a[i],i]for i in range(n)]

    aa.sort(key = lambda x : x[0])
    for i in range(n):
        aa[i][0]=i+1
    aa.sort(key = lambda x : x[1])
    b=[aa[i][0] for i in range(len(a))]
    return b

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans

def Zeros(a,b):
    if(b<=-1):
        return [0 for i in range(a)]
    else:
        return [[0 for i in range(b)] for i in range(a)]

def AddV2(v,w):
    return [v[0]+w[0],v[1]+w[1]]

dir4 = [[1,0],[0,1],[-1,0],[0,-1]]


def clamp(x,y,z):
    return max(y,min(z,x))

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
            
#
def Zaatsu(a):
    a.sort()
    now = a[0][0]
    od = 0
    for i in range(n):
        if(now==a[i][0]):
            a[i][0]=od
        else:
            now = a[i][0]
            od+=1
            a[i][0] = od
    
    a.sort(key = lambda x : x[1])
    return a

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)


'''
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 2
N = 10 ** 6 + 2
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

'''

def rl(x):
    return range(len(x))

# a = list(map(int, input().split()))

#################################################
#################################################
#################################################
#################################################


#11-

n = int(input())

aa = list(map(int, input().split()))
t = [0 for i in range(13)]
a=[]

for i in aa:
    if(i==0):
        print(0)
        exit()
    if(t[i]<=1):
        t[i]+=1
        a.append(i)
    elif(t[i]==2):
        print(0)
        exit()
#print(a)
n = len(a)
if(t[1]>=1):
    print(1)
    exit()

b = [0 for i in range(25)]
ans = 0
count = 0

for i in range(2**(n-1)):
    count +=1
    for j in range(25):
        b[j]=0
    b[0]=1
    b[24]=1
    for j in range(n):
        if((i>>j) & 1):
            b[24-a[j]] += 1
        else:
            b[a[j]] += 1
    minim = 24
    prev = -24
    for j in range(0,25):
        if(b[j]==1):
            minim = min(minim, j-prev)
            prev = j
        elif(b[j]>=2):
            minim = 0
            break
    ans = max(ans,minim)
    #print(b)

print(ans)
#print(count)

Submission status: Accepted

Solution code:
n = int(input())
ns = list(map(int, input().split()))
ns = sorted(ns)
ans = [0] * 24
ans[0] = 1
for i in range(n):
    if i % 2 == 0:
        ans[ns[i]] += 1
    else:
        ans[(24 - ns[i]) % 24] += 1
for i in ans:
    if i >= 2:
        print(0)
        exit()
ans = ans[1:]
print(1+min(len(i) for i in ''.join(map(str, ans)).split('1')))

Submission status: Accepted

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

if n == 1:
    print(D[0])
    exit()

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

D = []
E = []
for i in range(13):
    if i != 0:
        if C[i] >= 3:
            print(0)
            exit()
        elif C[i] == 2:
            D.append(i)
            D.append(-i)
        elif C[i] == 1:
            E.append(i)
        else:
            continue
    else:
        if C[i] >= 2:
            print(0)
            exit()
        elif C[i] == 1:
            D.append(i)
        else:
            continue

p = len(D)
q = len(E)
#print(E)
import copy
if q == 0:
    ans = 25
    for i in range(p-1):
        for j in range(i+1, p):
            ans = min(ans, min(abs(D[i]-D[j]), 24-abs(D[i]-D[j])))
    print(ans)
else:
    ans = []
    for i in range(2**q):
        D_ = copy.copy(D)
        for j in range(q):
            if (i >> j)&1:
                D_.append(E[j])
            else:
                D_.append(-E[j])
        p = len(D_)
        temp = 25
        #print(D)
        for i in range(p-1):
            for j in range(i+1, p):
                temp = min(temp, min(abs(D_[i]-D_[j]), 24-abs(D_[i]-D_[j])))
        ans.append(temp)
    print(max(ans))

Submission status: Accepted

Solution code:
import sys
from collections import Counter


def input():
    return sys.stdin.readline().strip()


sys.setrecursionlimit(20000000)

MOD = 10 ** 9 + 7
INF = float("inf")


def main():
    N = int(input())
    D = list(map(int, input().split()))
    D.append(0)

    count = Counter(D)
    items = count.items()
    times = []
    times_def = []

    for k, v in items:
        if k == 0:
            if v >= 2:
                print(0)
                return
            else:
                times_def.append(0)

        elif k == 12:
            if v >= 2:
                print(0)
                return
            else:
                times_def.append(12)

        elif v == 2:
            times_def.append(24 - k)
            times_def.append(k)

        elif v >= 3:
            print(0)
            return

        else:
            times.append(k)
            continue
    answer = []
    for i in range(2 ** (len(times)) + 1):
        d = []
        ans = INF
        for j in range(len(times)):
            if (i >> j) & 1:
                d.append(24 - times[j])
            else:
                d.append(times[j])
        t = times_def + d
        # print(len(t))
        # print(t)
        for a in range(N):
            for b in range(a + 1, N + 1):
                diff = min(abs(t[a] - t[b]), 24 - (abs(t[a] - t[b])))
                if diff < ans:
                    ans = diff
        answer.append(ans)
    print(max(answer))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import copy
from collections import Counter

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def main():
    N = int(input())
    D = list(map(int, input().split())) + [0]
    c = Counter(D)
    times = []
    undecided = []
    for k, v in c.items():
        if k == 0 or k == 12:
            if v > 1:
                print(0)
                return
            else:
                times.append(k)
                continue

        if v > 2:
            print(0)
            return
        elif v == 2:
            times.append(k)
            times.append(24 - k)
        else:
            undecided.append(k)

    ans = 0
    n = len(undecided)
    for pattern in range(2 ** n):
        tmp = copy.deepcopy(times)
        for i in range(n):
            if pattern & (1 << i):
                tmp.append(undecided[i])
            else:
                tmp.append(24 - undecided[i])

        L = len(tmp)
        diff = INF
        for i in range(L):
            for j in range(i + 1, L):
                d = abs(tmp[i] - tmp[j])
                d = min(d, 24 - d)

                if d < diff:
                    diff = d

        if diff > ans:
            ans = diff

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
d = list(map(int,input().split()))
d.sort()
for i,j in enumerate(d):
    if i%2==0:
        d[i] = 24-j
d.sort()
ans = d[0]
for i in range(1,n):
    tmp = d[i]-d[i-1]
    ans = min(ans,tmp)

ans = min(ans,24-d[-1])
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
def main():
    n = int(input())
    d = list(map(int, input().split()))
    d.sort()
    q = []
    q = deque(q)
    q.append(0)
    ans = float("inf")
    for v in d:
        if q[0]-(-v) < v-q[-1]:
            ans = min(ans, v-q[-1])
            q.append(v)
        else:
            ans = min(ans, q[0]-(-v))
            q.appendleft(-v)
    ans = min(ans, q[0]-(-12) + 12-q[-1])
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# input()
# int(input())
# map(int, input().split())
# list(map(int, input().split()))
import math
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)
from collections import deque

inf = 10 ** 15
mod = 10 ** 9 + 7

n = int(input())
d = list(map(int, input().split()))
Dlist = [0 for i in range(12)]
for num in d:
    if num == 0:
        print(0)
        sys.exit()
    Dlist[num-1]+=1
    if Dlist[num-1] == 3:
        print(0)
        sys.exit()
judge = [0]
unknown = []
if Dlist[11] >= 2:
    print(0)
    sys.exit()
elif Dlist[11] == 1:
    judge.append(12)
for i,num in enumerate(Dlist[1:11]):
    if num == 2:
        judge.append(i+2)
        judge.append(24-i-2)
    if num == 1:
        unknown.append(i+1)
nujeng = len(unknown)
ans = 0
for i in range(2**nujeng):
    tmp = []
    for num in judge:
        tmp.append(num)
    for j in range(nujeng):
        dnow = unknown[j]
        if ((i >> j) & 1):
            tmp.append(dnow+1)
        else:
            tmp.append(24-dnow-1)
    dic = 50
    if tmp:
        tmp.sort()
        pre = -inf
        for num in tmp:
            if num-pre < dic:
                dic = num-pre
            pre = num
        if 24-tmp[-1] < dic:
            dic = 24-tmp[-1]
        ans = max(dic, ans)
print(ans)

Submission status: Accepted

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

"""
愚直に解くと
・時差が0,12以外の人は、D, 24-Dの2パターンの時間になりうる
・なので、2^N全部試す
で、普通にTLE。

例えばある時差Dの人が
（１）一人の場合：時刻Dとする
（２）二人の場合：Dと24-Dで振り分ける
で、最小の時差を減らさない動きができる
一方で
（３）三人以上の場合：Dと24-Dの少なくとも一方が２人以上いることになるから、時差の最小値が0になる

なので、時差Dが一人の時は、Dと24-Dで２通り試して、時差Dが二人の時は両方に入れる、３人以上は問答無用で0になる、みたいにするとよさげ
あるいは最初はDとして、次は24-Dとして～みたいなのを繰り返す。
"""

from collections import Counter
from collections import defaultdict

c = Counter(D)
c[0] += 1

for i in range(13):
    if i == 0 or i == 12:
        if c[i] >= 2:
            print(0)
            exit()
    else:
        if c[i] >= 3:
            print(0)
            exit()

D.sort()

d = defaultdict(int)
d[24] += 1
is_am = True
for t in D:
    if is_am:
        d[t] += 1
        is_am = False
    else:
        d[24 - t] += 1
        is_am = True


ans = min(D)
times = list(d.keys())
times.sort()
for a,b in zip(times, times[1:]):
    ans = min(ans, b-a)

print(ans)

Submission status: Accepted

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

T = [0]*13
T[0] = 1
for d in D:
    T[d] += 1


Times = [0]*24
ones =[]
for i,t in enumerate(T):
    if t>=3 or (t==2 and (i==0 or i==12)):
        print(0)
        exit()
    elif t==2:
        Times[i] = 1
        Times[24-i] = 1
    elif t==1:
        ones.append(i)

ans = 0
L = len(ones)
for i in range(2**L):
    stats = [False]*L
    temp = i
    for j in range(L):
        stats[j] = temp&1
        temp >>= 1
    
    newTime = [t for t in Times]
    res = 10**9
    for j,t in enumerate(ones):
        nt = t if stats[j] else (24-t)%24
        newTime[nt] = 1
    
    gaps = []
    for j,t in enumerate(newTime):
        if t!=0:
            gaps.append(j)
    for j in range(len(gaps)-1):
        res = min(res,min(gaps[j+1]-gaps[j],gaps[j]+24-gaps[j+1]))
    if len(gaps)>=2:
        res = min(res, gaps[0]+24-gaps[-1])
    ans = max(ans, res)
print(ans)

Submission status: Accepted

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

D.sort()
T = []
for i,d in enumerate(D):
    if i % 2 == 1:
        d = 24- d
    T.append(d)

T.sort()
T = [0] + T
MIN = 24
for i in range(N):
    diff = T[i+1] - T[i]
    MIN = min(diff,MIN)
print(MIN)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n, *d = map(int, read().split())
d.sort()
p = [0, 24]
m = [0, 24]
for i, dd in enumerate(d):
    if i % 2 == 0:
        p.append(dd)
        m.append(24 - dd)
    else:
        p.append(24 - dd)
        m.append(dd)
pp, mm = float('inf'), float('inf')
p.sort()
m.sort()
for (bp, ap, bm, am) in zip(p, p[1:], m, m[1:]):
    pp = min(pp, ap - bp)
    mm = min(mm, am - bm)
print(max(pp, mm))

Submission status: Accepted

Solution code:
N=int(input())
D=list(map(int,input().split())) +[0]
from collections import Counter
cnt=Counter(D)

if cnt[0]>=2 or cnt[12]>=2:
    print(0)
    exit()

if any(v>=3 for v in cnt.values()):
    print(0)
    exit()

ans=0
for b in range(1<<11):
    ts=[0]*24
    ts[0]=1
    if cnt[12]:
        ts[12]=1
    for i in range(11):
        t=i+1
        if cnt[t]==0:
            continue
        if cnt[t]==2:
            ts[t]=ts[24-t]=1
            continue
        if b&(1<<i):
            ts[t]=1
        else:
            ts[24-t]=1
    tt=[i for i,b in enumerate(ts) if b]
    tmp=24-tt[-1]
    for t1,t2 in zip(tt,tt[1:]):
        tmp=min(tmp,t2-t1)
    ans=max(tmp,ans)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
d = [0]*13
for i in map(int,input().split()):
  if i == 0:
    print(0)
    exit()
  d[i] += 1
t = [0]*25
t[0] = t[-1] = 1
c = 0
for i,j in enumerate(d):
  if j >=3:
    print(0)
    exit()
  elif j == 0:
    continue
  elif j == 2:
    t[i] = t[24-i] = 1
  else:
    if c == 0:
      t[i] = 1
    else:
      t[24-i] = 1
    c = 1-c
m = 24
ans = 24
for i in t:
  m += 1
  if i:
    ans = min(ans,m)
    m = 0
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=[0]+list(map(int,input().split()))
a.sort()
for i in range(n-1):
	if a[i]==a[i+1]==a[i+2]:
		print(0)
		exit()
double=[]
for i in range(n):
	if a[i]==a[i+1]:
		if a[i]==12 or a[i]==0:
			print(0)
			exit()
		else:
			double.append(a[i])
a=set(a);a=list(a)
b=[]
for x in a:
	if x not in double:
		b.append(x)
from copy import copy
a=copy(b)
n=len(a)
ans=0
def two(x):
	return (n-len(bin(x)[2:]))*"0"+bin(x)[2:]
for i in range(2**n):
	r=two(i)
	time=[0]*24
	time[0]=1
	for x in double:
		time[x]=1
		time[24-x]=1
	for j in range(n):
		if r[j]=="1":
			time[a[j]]=1
		else:
			if a[j]!=0:
				time[24-a[j]]=1
			else:
				time[0]=1
	pre_ans=24
	ren=0
	for j in range(1,24):
		if time[j]==0:
			ren+=1
		else:
			pre_ans=min(pre_ans,ren)
			ren=0
	pre_ans=min(pre_ans,ren)
	ans=max(ans,pre_ans+1)
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

n = int(input())
D = [0] + list(map(int, input().split()))

C = Counter(D)

if C[0] >= 2 or C[12] >= 2 or any(v >= 3 for v in C.values()):
  print(0)
  exit()
  
ans = 0
for b in range(1<<11):
  T = []
  T.append(0)
  if C[12]:
    T.append(12)
  for i in range(11):
    if C[i + 1] == 2:
      T.append(i + 1)
      T.append(24 - (i + 1))
    else:
      if C[i + 1] == 1:
        if b & (1 << i):
          T.append(i + 1)
        else:
          T.append(24 - (i + 1))
  T.sort()
  T = T + [24]
  tmp = min(j - i for i, j in zip(T, T[1:]))
  ans = max(ans, tmp)
print(ans)

Submission status: Accepted

Solution code:


from collections import Counter
from collections import defaultdict

N = map(int, input().split())
D = list(map(int, input().split()))




c = Counter(D)

c[0] += 1
# 高橋君と同じ時間帯の人が一人でもいれば、時差の最小は常に0
if c[0] >= 2:
    print(0)
    exit(0)

# 高橋君との時差がdの人が3人以上いる場合も、時差の最小は常に0（同じ時間帯の都市に二人以上いることになるから）
for i in c.values():
    if i >= 3:
        print(0)
        exit()


times = defaultdict(int)

# 0時との時間差をとるときに24がいたほうがよいか？なくてもいいか。
c[24] += 1
before_12 = True
D.sort()
for d in D:
    if before_12:
        times[d] += 1
        before_12 = False
    else:
        times[24-d] += 1
        before_12 = True


# 高橋君との時差で答えを初期化
ans = min(D)

tlst = list(times.keys())
tlst.sort()

for a,b in zip(tlst, tlst[1:]):
    ans = min(ans, b - a)

print(ans)