s_id
stringlengths
10
10
p_id
stringlengths
6
6
u_id
stringlengths
10
10
date
stringlengths
10
10
language
stringclasses
1 value
original_language
stringclasses
11 values
filename_ext
stringclasses
1 value
status
stringclasses
1 value
cpu_time
stringlengths
1
5
memory
stringlengths
1
7
code_size
stringlengths
1
6
code
stringlengths
1
539k
s776819136
p02242
u845643816
1511969133
Python
Python3
py
Runtime Error
0
0
742
rootList = [-1 for i in range(n)] parent = [0 for i in range(n)] lenList = [float("inf") for i in range(n)] lenList[0] = 0 def getRoot(x): r = rootList[x] if r < 0: rootList[x] = x elif r != x: rootList[x] = getRoot(r) return rootList[x] flag = True while flag: flag = False edgeList.sort(key=lambda x: (x[0] + lenList[x[1]])) for e in edgeList: # weight:e[0], e[1]->e[2] if e[2] == 0: continue x = getRoot(e[1]) y = getRoot(e[2]) if x == 0 != y: parent[e[2]] = e[1] lenList[e[2]] = lenList[e[1]] + e[0] rootList[y] = 0 flag = True break for i, j in zip(range(n), lenList): print(i, j)
s945333322
p02242
u626266743
1511970077
Python
Python3
py
Runtime Error
0
0
940
from sys import stdin INFTY = 1 << 21 WHITE = 0 GRAY = 1 BLACK = 2 n = int(stdin.readline()) M = [[INFTY for i in range(n)] for j in range(n)] for u in range(n): U = list(map(int, stdin.readline().split()[2:])) for j in range(0, len(U), 2): M[u][U[j]] = U[j+1] d = [INFTY for i in range(n)] color = [WHITE for i in range(n)] def dijkstra(): global n d[0] = 0 color[0] = GRAY while(1): minv = INFTY u = -1 for i in range(n): if (minv > d[i] and color[i] != BLACK): u = i minv = d[i] if (u == -1): break color[u] = BLACK for v in range(n): if (color[v] != BLACK and M[u][v] != INFTY): if(d[v] > d[u] + M[u][v]:) d[v] = d[u] + M[u][v] color[v] = GRAY for i in range(n): print(i, (-1 if d[i] == INFTY else d[i])) dijkstra()
s329299363
p02242
u626266743
1511970106
Python
Python3
py
Runtime Error
0
0
926
from sys import stdin INFTY = 1 << 21 WHITE = 0 GRAY = 1 BLACK = 2 n = int(stdin.readline()) M = [[INFTY] * n for i in range(n)] for u in range(n): U = list(map(int, stdin.readline().split()[2:])) for j in range(0, len(U), 2): M[u][U[j]] = U[j+1] d = [INFTY for i in range(n)] color = [WHITE for i in range(n)] def dijkstra(): global n d[0] = 0 color[0] = GRAY while(1): minv = INFTY u = -1 for i in range(n): if (minv > d[i] and color[i] != BLACK): u = i minv = d[i] if (u == -1): break color[u] = BLACK for v in range(n): if (color[v] != BLACK and M[u][v] != INFTY): if(d[v] > d[u] + M[u][v]:) d[v] = d[u] + M[u][v] color[v] = GRAY for i in range(n): print(i, (-1 if d[i] == INFTY else d[i])) dijkstra()
s010523309
p02242
u626266743
1511970367
Python
Python3
py
Runtime Error
0
0
952
from sys import stdin INFTY = 1 << 21 WHITE = 0 GRAY = 1 BLACK = 2 n = int(stdin.readline()) M = [[INFTY for i in range(n)] for j in range(n)] for u in range(0, n): U = list(map(int, stdin.readline().split()[2:])) for j in range(0, len(U), 2): M[u][U[j]] = U[j+1] d = [INFTY for i in range(n)] color = [WHITE for i in range(n)] def dijkstra(): global n d[0] = 0 color[0] = GRAY while(1): minv = INFTY u = -1 for i in range(0, n): if (minv > d[i] and color[i] != BLACK): u = i minv = d[i] if (u == -1): break color[u] = BLACK for v in range(0, n): if (color[v] != BLACK and M[u][v] != INFTY): if(d[v] > d[u] + M[u][v]:) d[v] = d[u] + M[u][v] color[v] = GRAY for i in range(0, n): print(i, (-1 if d[i] == INFTY else d[i])) dijkstra()
s638264617
p02243
u007270338
1530999457
Python
Python3
py
Runtime Error
0
0
1585
#coding:utf-8 import numpy as np n = int(input()) inf = 1000000000000000 def minHeapify(Q,i): H = len(Q) l = 2*i r = 2*i + 1 if l < H and Q[l][1] < Q[i][1]: smallest = l else: smallest = i if r < H and Q[r][1] < Q[smallest][1]: smallest = r if smallest != i: Q[i], Q[smallest] = Q[smallest], Q[i] minHeapify(Q,smallest) def buildMinHeap(Q): H = len(Q) for i in range(H // 2, -1, -1): minHeapify(Q,i) def Insert(Q,key): v = key[0] Q.append([v,inf]) lens = len(Q) heapIncreaseKey(Q,lens-1,key) def heapIncreaseKey(Q,i,key): Q[i][1] = key[1] while i > 0 and Q[i // 2][1] > Q[i][1]: Q[i], Q[i // 2] = Q[i // 2], Q[i] i //= 2 def heapExtractMin(Q): H = len(Q) minv = Q[0][0] Q[0] = Q[H-1] Q.pop() minHeapify(Q,0) return minv def dijkstra(s): color = ["white" for i in range(n)] d = [inf for i in range(n)] d[s] = 0 Q = [[s,0]] while Q != []: u = heapExtractMin(Q) color[u] = "black" for vw in mtrx[u]: [v,w] = vw if color[v] != "black": if d[u] + w < d[v]: d[v] = d[u] + w color[v] = "gray" Insert(Q,[v,d[v]]) return d mtrx = [[] for i in range(n)] for i in range(n): col = list(map(int,input().split())) u,k = col[0], col[1] for j in range(k): [v,w] = col[2*j+2: 2*j+4] mtrx[u].append([v,w]) d = dijkstra(0) for i,j in enumerate(d): print(i,j)
s762706872
p02243
u007270338
1530999477
Python
Python3
py
Runtime Error
0
0
1585
#coding:utf-8 import numpy as np n = int(input()) inf = 1000000000000000 def minHeapify(Q,i): H = len(Q) l = 2*i r = 2*i + 1 if l < H and Q[l][1] < Q[i][1]: smallest = l else: smallest = i if r < H and Q[r][1] < Q[smallest][1]: smallest = r if smallest != i: Q[i], Q[smallest] = Q[smallest], Q[i] minHeapify(Q,smallest) def buildMinHeap(Q): H = len(Q) for i in range(H // 2, -1, -1): minHeapify(Q,i) def Insert(Q,key): v = key[0] Q.append([v,inf]) lens = len(Q) heapIncreaseKey(Q,lens-1,key) def heapIncreaseKey(Q,i,key): Q[i][1] = key[1] while i > 0 and Q[i // 2][1] > Q[i][1]: Q[i], Q[i // 2] = Q[i // 2], Q[i] i //= 2 def heapExtractMin(Q): H = len(Q) minv = Q[0][0] Q[0] = Q[H-1] Q.pop() minHeapify(Q,0) return minv def dijkstra(s): color = ["white" for i in range(n)] d = [inf for i in range(n)] d[s] = 0 Q = [[s,0]] while Q != []: u = heapExtractMin(Q) color[u] = "black" for vw in mtrx[u]: [v,w] = vw if color[v] != "black": if d[u] + w < d[v]: d[v] = d[u] + w color[v] = "gray" Insert(Q,[v,d[v]]) return d mtrx = [[] for i in range(n)] for i in range(n): col = list(map(int,input().split())) u,k = col[0], col[1] for j in range(k): [v,w] = col[2*j+2: 2*j+4] mtrx[u].append([v,w]) d = dijkstra(0) for i,j in enumerate(d): print(i,j)
s843155929
p02243
u684241248
1531715759
Python
Python3
py
Runtime Error
0
0
4593
# -*- coding: utf-8 -*- from collections import defaultdict from heapq import heappop, heappush def dijkstra(edges, start, *, adj_matrix=False, default_value=float('inf')): ''' Returns best costs to each node from 'start' node in the given graph. (Single Source Shortest Path - SSSP) If edges is given as an adjacency list including costs and destination nodes on possible edges, adj_matrix should be False(default), and it is generally when this functions works much faster. Note that costs in edges should follow the rules below 1. The cost from a node itself should be 0, 2. If there is no edge between nodes, the cost between them should be default_value 3. The costs can't be negative # sample input when given as adjacency list (adj_matrix=False) edges = [[(1, 2), (2, 5), (3, 4)], # node 0 [(0, 2), (3, 3), (4, 6)], # node 1 [(0, 5), (3, 2), (5, 6)], # node 2 [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3 [(1, 6), (3, 2), (5, 4)], # node 4 [(2, 6), (4, 4)]] # node 5 # sample input when given as adjacency matrix (adj_matrix=True) edges = [[0, 2, 5, 4, inf, inf], # node 0 [2, 0, inf, 3, 6, inf], # node 1 [5, inf, 0, 2, inf, 6], # node 2 [4, 3, 2, 0, 2, inf], # node 3 [inf, 6, inf, 2, 0, 4], # node 4 [inf, inf, 6, inf, 4, 0]] # node 5 ''' n = len(edges) inf = float('inf') # costs = [inf] * n costs = defaultdict(lambda: inf) costs[start] = 0 pq, rem = [(0, start)], n - 1 while pq and rem: tmp_cost, tmp_node = heappop(pq) if costs[tmp_node] < tmp_cost: continue rem -= 1 nxt_edges = ((node, cost) for node, cost in enumerate(edges[tmp_node]) if cost != default_value) if adj_matrix else\ edges[tmp_node] for nxt_node, nxt_cost in nxt_edges: new_cost = tmp_cost + nxt_cost if costs[nxt_node] > new_cost: costs[nxt_node] = new_cost heappush(pq, (new_cost, nxt_node)) return costs def dijkstra_route(edges, start, goal, *, adj_matrix=False, default_value=float('inf'), verbose=False): ''' Trys to find the best route to the 'goal' from the 'start' ''' n = len(edges) inf = float('inf') # costs = [inf] * n costs = defaultdict(lambda: inf) costs[start] = 0 pq, rem = [(0, start)], n - 1 # prevs = [-1 for _ in [None] * n] prevs = defaultdict(lambda: -1) while pq and rem: tmp_cost, tmp_node = heappop(pq) if costs[tmp_node] < tmp_cost: continue rem -= 1 nxt_edges = ((node, cost) for node, cost in enumerate(edges[tmp_node]) if cost != default_value) if adj_matrix else\ edges[tmp_node] for nxt_node, nxt_cost in nxt_edges: new_cost = tmp_cost + nxt_cost if costs[nxt_node] > new_cost: costs[nxt_node] = new_cost heappush(pq, (new_cost, nxt_node)) prevs[nxt_node] = tmp_node min_route = [] prev = goal cnt = 0 while prev != start: min_route.append(prev) prev = prevs[prev] cnt += 1 if prev == -1 or cnt > n: raise NoRouteError( 'There is no possible route in this graph \nedges: {} \nstart: {} \ngoal: {}'. format(edges, start, goal)) else: min_route.append(prev) min_route = min_route[::-1] min_cost = costs[goal] if verbose: print('---route---') for node in min_route[:-1]: print('{} -> '.format(node), end='') else: print(min_route[-1]) print('---distance---') print(min_cost) return costs, min_route class NoRouteError(Exception): pass if __name__ == '__main__': ''' an example of using this function AIZU ONLINE JUDGE - ALDS_1_12_C ''' n = int(input()) edges = [[] for i in range(n)] for i in range(n): i, k, *kedges = map(int, input().split()) for edge in zip(kedges[::2], kedges[1::2]): edges[i].append(edge) # for i, cost in enumerate(dijkstra(edges, 0)): # print(i, cost) for i, cost in dijkstra(edges, 0): print(i, cost)
s176385792
p02243
u567380442
1422449899
Python
Python3
py
Runtime Error
600
7172
519
import io, sys, itertools f = sys.stdin def take2(iterable): i = iter(iterable) while True: yield next(i), next(i) n = int(f.readline()) adj =[[(v, c) for v, c in take2(map(int, f.readline().split()[2:]))] for _ in range(n)] d = [100000 * 100 + 1] * n d[0] = 0 def search(parent, children): global d for v, c in children: if d[v] > d[parent] + c: d[v] = d[parent] + c search(v, adj[v]) search(0, adj[0]) for i in range(n): print(i, d[i])
s741918244
p02243
u177808190
1455082265
Python
Python
py
Runtime Error
10
6488
901
MAX = 100 INF = 1000000 WHITE = 0 GRAY = 1 BLACK = 2 n = int(raw_input()) M = [[INF for i in range(n)]for j in range(n)] d = [INF for i in range(MAX)] Color = [WHITE for i in range(MAX)] for i in range(n): tmp = map(int,raw_input().split()) u = tmp[0] k = tmp[1] for j in range(1, k + 1): v = tmp[j * 2] c = tmp[j * 2 + 1] M[u][v] = c #def dijkstra(): d[0] = 0 Color[0] = GRAY while True: minv = INF u = -1 for i in range(n): if minv > d[i] and Color[i] != BLACK: u = i minv = d[i] if u == -1: break Color[u] = BLACK for v in range(n): if Color[v] != BLACK and M[u][v] != INF: if d[v] > d[u] + M[u][v]: d[v] = d[u] + M[u][v] Color[v] = GRAY for i in range(n): print i, if d[i] == INF: print -1 else: print d[i]
s552386463
p02243
u138577439
1486893329
Python
Python3
py
Runtime Error
0
0
690
V=int(input()) G=[[] for i in range(V)] d=[1001001001 for i in range(V)] used=[False for i in range(V)] import heapq def dijkstra(s): q=[] d[s]=0 heapq.heappush(q,(0, s)) while(len(q)): p=heapq.heappop(q) v=p[1] used[v]=true if d[v]<p[0]: continue for e in G[v]: if (not used[e[0]]) and d[e[0]]>d[v]+e[1]: d[e[0]]=d[v]+e[1] heapq.heappush(q, (d[e[0]], e[0])) import sys for l in sys.stdin: l=list(map(int,l.split())) u=l[0] k=l[1] G[u]=zip(*[iter(l[2:])]*2) dijkstra(0) for i, c in enumerate(d): print(i, d[i])
s922390877
p02243
u798803522
1511064737
Python
Python3
py
Runtime Error
0
0
818
from collections import defaultdict import heapq v_num = int(input()) connect = defaultdict(list) for _ in range(v_num): que = [int(n) for n in input().split(" ")] connect[que[0]] = [[v, w] for v, w in zip(que[2:len(que):2], que[3:len(que):2]) # weight_edge[que[0]] = {k:v for k, v in zip(que[2:len(que):2], que[3:len(que):2])} queue = [] heapq.heapify(queue) heapq.heappush(queue, [0, 0]) distance = [-1 for n in range(v_num)] went = 0 visited = set() while went < v_num: q = heapq.heappop(queue) weight, here = q if here in visited: continue visited |= {here} went += 1 distance[here] = weight for conn in connect[here]: if conn[0] not in visited: heapq.heappush(queue, [weight + conn[1], conn[0]]) for i in range(v_num): print(i, distance[i])
s017238616
p02243
u150984829
1520418592
Python
Python3
py
Runtime Error
0
0
352
import sys from heapq import* e=sys.stdin.readline I=float("inf") def m(): n=int(e()) A=[] for _ in[0]*n: e=list(map(int,e().split())) A+=[zip(e[2::2],e[3::2])] d=[0]+[I]*n H=[(0,0)] while H: u=heappop(H)[1] for v,c in A[u]: t=d[u]+c if d[v]>t: d[v]=t heappush(H,(t,v)) print('\n'.join(f'{i} {d[i]}'for i in range(n))) m()
s626456910
p02243
u792145349
1525228743
Python
Python3
py
Runtime Error
0
0
1403
N = int(input()) G = [[] for i in range(N)] for nod in range(N): tmp = list(map(int, input().split())) for i in range(2, tmp[1]*2+1, 2): edge, cos = tmp[i], tmp[i+1] G[nod].append([edge, cos]) import heapq def dijkstra(x): d = [float('inf')] * N d[x] = 0 visited = {x} # d, u hq = [(0, x)] while hq: u = heapq.heappop(hq)[1] visited.add(u) for node, cost in G[u]: if (node not in visited) and d[node] > d[u] + cost: d[node] = d[u] + cost heapq.heappush(hq, (d[u]+cost, node)) return d distance = dijkstra(0) #print(distance) for i in range(N): print(i, distance[i]) N = int(input()) G = [[] for i in range(N)] for nod in range(N): tmp = list(map(int, input().split())) for i in range(2, tmp[1]*2+1, 2): edge, cos = tmp[i], tmp[i+1] G[nod].append([edge, cos]) import heapq def dijkstra(x): d = [float('inf')] * N d[x] = 0 visited = {x} # d, u hq = [(0, x)] while hq: u = heapq.heappop(hq)[1] visited.add(u) for node, cost in G[u]: if (node not in visited) and d[node] > d[u] + cost: d[node] = d[u] + cost heapq.heappush(hq, (d[u]+cost, node)) return d distance = dijkstra(0) #print(distance) for i in range(N): print(i, distance[i])
s314243013
p02243
u126478680
1526027537
Python
Python3
py
Runtime Error
30
6368
1139
from heapq import heappush, heappop from enum import Enum, auto INFTY = float('inf') class Color(Enum): WHITE = auto() GRAY = auto() BLACK = auto() n = int(input()) M = [[-1 for i in range(n)] for i in range(n)] adj_list = [] for i in range(n): u, k, *kv = list(map(int, input().split(' '))) if k == 0: continue adj_list.append(kv) for j in range(0,2*k,2): M[i][kv[j]] = kv[j+1] colors = [] d = [] def dijkstra(s): global d colors = [Color.WHITE for i in range(n)] d = [INFTY for i in range(n)] pque = [] d[0] = 0 heappush(pque, (0, s)) while len(pque) >= 1: vert_u = heappop(pque) u = vert_u[1] colors[u] = Color.BLACK if d[u] < vert_u[0]: continue i = 0 while i <= len(adj_list[u])-2: v = adj_list[u][i] if colors[v] != Color.BLACK: if d[u] + adj_list[u][i+1] < d[v]: d[v] = d[u] + adj_list[u][i+1] colors[v] = Color.GRAY heappush(pque, (d[v], v)) i += 2 dijkstra(0) for i in range(n): print(i, d[i])
s325614994
p02244
u726330006
1540483492
Python
Python3
py
Runtime Error
30
5640
2495
class Chess_board: def __init__(self): self.board=[[0]*8 for i in range(8)] self.queen_array=[] self.queen_row=[] def copy_board(chess_board): new_board=Chess_board() new_board.board=[chess_board.board[i][:] for i in range(8)] new_board.queen_array=chess_board.queen_array[:] new_board.queen_row=chess_board.queen_row[:] return new_board def mk_board(chess_board,queen_array): for queen in queen_array: row=queen[0] col=queen[1] if(chess_board.board[row][col]==0): chess_board.queen_array.append(queen) chess_board.queen_row.append(row) for i in range(8): chess_board.board[row][i]=1 for i in range(8): chess_board.board[i][col]=1 for i in range(1,8): if(row - i >=0 and col - i >=0): chess_board.board[row-i][col-i]=1 else: break for i in range(1,8): if(8 > row + i >=0 and col - i >=0): chess_board.board[row+i][col-i]=1 else: break for i in range(1,8): if(row - i >=0 and 8 > col + i >=0): chess_board.board[row-i][col+i]=1 else: break for i in range(1,8): if(8 > row + i >=0 and 8 > col + i >=0): chess_board.board[row+i][col+i]=1 else: break else: return 0 return 1 def find_queen(chess_board): for tmp_row in range(8): if(tmp_row in chess_board.queen_row): pass else: break for col in range(8): new_board=copy_board(chess_board) if(mk_board(new_board,[[tmp_row,col]])==1): if(len(new_board.queen_row)==8): return new_board else: result=find_queen(new_board) if(result is not None): return result return None n=int(input()) queen_array=[] for i in range(n): queen_array.append(list(map(int,input().split()))) board=Chess_board() mk_board(board,queen_array) result_board=find_queen(board) for i in range(8): for queen in result_board.queen_array: if(queen[0]==i): str1="."*queen[1] str2="."*(7-queen[1]) print(f"{str1}Q{str2}")
s611336135
p02244
u726330006
1540483589
Python
Python3
py
Runtime Error
30
5640
2523
class Chess_board: def __init__(self): self.board=[[0]*8 for i in range(8)] self.queen_array=[] self.queen_row=[] def copy_board(chess_board): new_board=Chess_board() new_board.board=[chess_board.board[i][:] for i in range(8)] new_board.queen_array=chess_board.queen_array[:] new_board.queen_row=chess_board.queen_row[:] return new_board def mk_board(chess_board,queen_array): for queen in queen_array: row=queen[0] col=queen[1] if(chess_board.board[row][col]==0): chess_board.queen_array.append(queen) chess_board.queen_row.append(row) for i in range(8): chess_board.board[row][i]=1 for i in range(8): chess_board.board[i][col]=1 for i in range(1,8): if(row - i >=0 and col - i >=0): chess_board.board[row-i][col-i]=1 else: break for i in range(1,8): if(8 > row + i >=0 and col - i >=0): chess_board.board[row+i][col-i]=1 else: break for i in range(1,8): if(row - i >=0 and 8 > col + i >=0): chess_board.board[row-i][col+i]=1 else: break for i in range(1,8): if(8 > row + i >=0 and 8 > col + i >=0): chess_board.board[row+i][col+i]=1 else: break else: return 0 return 1 def find_queen(chess_board): for tmp_row in range(8): if(tmp_row in chess_board.queen_row): pass else: break for col in range(8): new_board=copy_board(chess_board) if(mk_board(new_board,[[tmp_row,col]])==1): if(len(new_board.queen_row)==8): return new_board else: result=find_queen(new_board) if(result is not None): return result return None n=int(input()) queen_array=[] for i in range(n): queen_array.append(list(map(int,input().split()))) board=Chess_board() mk_board(board,queen_array) if(board.queen_row!=8): result_board=find_queen(board) for i in range(8): for queen in result_board.queen_array: if(queen[0]==i): str1="."*queen[1] str2="."*(7-queen[1]) print(f"{str1}Q{str2}")
s941291079
p02244
u408260374
1456536051
Python
Python3
py
Runtime Error
0
0
521
import itertools N, Q, row, col = input(), [], range(8), range(8) for _ in range(N): r, c = map(int, raw_input().split()) Q.append((r, c)) row.remove(r) col.remove(c) for l in itertools.permutations(col): queen = Q + list(zip(row, l)) if not any((r1 != r2 or c1 != c2) and (r1 == r2 or c1 == c2 or r1 + c1 == r2 + c2 or r1 - c1 == r2 - c2) for r2, c2 in queen for r1, c1 in queen): print '\n'.join(''.join('Q' if (r, c) in queen else '.' for c in range(8)) for r in range(8)) break
s562262020
p02244
u533883485
1502107072
Python
Python3
py
Runtime Error
30
7920
2819
# coding=utf-8 class Tree(): def __init__(self, init_field): self.root = init_field def search(self, field_id, field): global final_queen_pos #print("field_id:", field_id) #field.print_field() q_r = rest_row[field_id - n] if final_queen_pos: return None else: for q_c, cell in enumerate(field.state[q_r]): if cell == 0: if final_queen_pos: break if field_id == 7: field.queen_pos.append([q_r, q_c]) final_queen_pos = field.queen_pos break else: next_field = Field(field_id + 1, field) field.children.append(next_field) next_field.update(q_r, q_c) self.search(field_id + 1, next_field) else: continue class Field(): def __init__(self, field_id, parent=None): self.id = field_id self.parent = parent self.children = [] if field_id == 0: self.state = [[0 for _ in range(W)] for H in range(H)] self.queen_pos = [] else: self.state = [] self.queen_pos = [] for row in self.parent.state: x = row.copy() self.state.append(x) for parent_queen_pos in self.parent.queen_pos: self.queen_pos.append(parent_queen_pos) def update(self, q_r, q_c): self.queen_pos.append([q_r, q_c]) for i in range(8): self.state[q_r][i] = 1 self.state[i][q_c] = 1 summ = q_c + q_r diff = q_c - q_r for i in range(8): if (0 <= i + diff < 8): self.state[i][i + diff] = 1 if (0 <= summ - i < 8): self.state[i][summ - i] = 1 def print_field(self): #for debug print("queen_pos:", self.queen_pos) for row in self.state: print(*row) H, W = 8, 8 n = int(input()) init_field = Field(0) tree = Tree(init_field) field_list = [init_field] rest_row = [i for i in range(8)] queen_pos = [] final_queen_pos = None final_result = [["." for _ in range(8)] for _ in range(8)] for _ in range(n): r, c = map(int, input().split()) queen_pos.append([r, c]) rest_row.remove(r) i = 0 prev_field = init_field for q_r, q_c in queen_pos: i += 1 field = Field(i, prev_field) field.update(q_r, q_c) field_list.append(field) prev_field.children = [field] prev_field = field tree.search(i, field) for q_r, q_c in final_queen_pos: final_result[q_r][q_c] = "Q" for row in final_result: print("".join(row), end = "\n")
s000031433
p02244
u466299927
1523959862
Python
Python3
py
Runtime Error
0
0
2384
# -*- coding: utf-8 -*- import sys BOARD_SIZE_W = 8 BOARD_SIZE_H = 8 def set_queen(board, queen_point): """ クイーンを指定座標に配置した後、残りの配置可能な位置の配列を返す """ return filter(create_queen_filter(queen_point), board) def create_queen_filter(queen_point): """ 指定位置にクイーンを配置したことにより、対象座標へ配置不可能にならないかを確認する関数を返す """ def queen_filter(new_point): return new_point[0] != queen_point[0] and \ new_point[1] != queen_point[1] and \ new_point[1] != new_point[0] + queen_point[1] - queen_point[0] and \ new_point[1] != -new_point[0] + queen_point[1] + queen_point[0] return queen_filter def get_board_string(queen_points): """ クイーンの位置座標の配列を指定出力形式に変換する """ queen_points_set = set(list(map(lambda point: "{}:{}".format(point[0], point[1]), queen_points))) board_string_lines = [] for y in range(BOARD_SIZE_H): line = "" for x in range(BOARD_SIZE_W): if "{}:{}".format(x, y) in queen_points_set: line += "Q" else: line += "." board_string_lines.append(line) return "\n".join(board_string_lines) def get_all_queen_points(board, queen_points): if len(queen_points) >= 8: return queen_points elif not board: return [] for empty_point in board: new_queen_points = [empty_point] new_queen_points.extend(queen_points) new_queen_points = get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) if new_queen_points: return get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) def main(): inputStr = sys.stdin.read() lines = inputStr.split("\n") if len(lines) <= 1: lines = [] else: lines = lines[1:] queen_points = list(map(lambda line: list(map(int, line.split(" "))), lines)) board = [[i % BOARD_SIZE_W, i // BOARD_SIZE_H] for i in range(BOARD_SIZE_H * BOARD_SIZE_W)] for queen_point in queen_points: board = set_queen(board, queen_point) print(get_board_string(get_all_queen_points(board, queen_points))) if __name__ == '__main__': main()
s034453482
p02244
u466299927
1523959895
Python
Python3
py
Runtime Error
0
0
2384
# -*- coding: utf-8 -*- import sys BOARD_SIZE_W = 8 BOARD_SIZE_H = 8 def set_queen(board, queen_point): """ クイーンを指定座標に配置した後、残りの配置可能な位置の配列を返す """ return filter(create_queen_filter(queen_point), board) def create_queen_filter(queen_point): """ 指定位置にクイーンを配置したことにより、対象座標へ配置不可能にならないかを確認する関数を返す """ def queen_filter(new_point): return new_point[0] != queen_point[0] and \ new_point[1] != queen_point[1] and \ new_point[1] != new_point[0] + queen_point[1] - queen_point[0] and \ new_point[1] != -new_point[0] + queen_point[1] + queen_point[0] return queen_filter def get_board_string(queen_points): """ クイーンの位置座標の配列を指定出力形式に変換する """ queen_points_set = set(list(map(lambda point: "{}:{}".format(point[0], point[1]), queen_points))) board_string_lines = [] for y in range(BOARD_SIZE_H): line = "" for x in range(BOARD_SIZE_W): if "{}:{}".format(x, y) in queen_points_set: line += "Q" else: line += "." board_string_lines.append(line) return "\n".join(board_string_lines) def get_all_queen_points(board, queen_points): if len(queen_points) >= 8: return queen_points elif not board: return [] for empty_point in board: new_queen_points = [empty_point] new_queen_points.extend(queen_points) new_queen_points = get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) if new_queen_points: return get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) def main(): inputStr = sys.stdin.read() lines = inputStr.split("\n") if len(lines) <= 1: lines = [] else: lines = lines[1:] queen_points = list(map(lambda line: list(map(int, line.split(" "))), lines)) board = [[i % BOARD_SIZE_W, i // BOARD_SIZE_H] for i in range(BOARD_SIZE_H * BOARD_SIZE_W)] for queen_point in queen_points: board = set_queen(board, queen_point) print(get_board_string(get_all_queen_points(board, queen_points))) if __name__ == '__main__': main()
s364185102
p02244
u466299927
1523959964
Python
Python3
py
Runtime Error
0
0
2384
# -*- coding: utf-8 -*- import sys BOARD_SIZE_W = 8 BOARD_SIZE_H = 8 def set_queen(board, queen_point): """ クイーンを指定座標に配置した後、残りの配置可能な位置の配列を返す """ return filter(create_queen_filter(queen_point), board) def create_queen_filter(queen_point): """ 指定位置にクイーンを配置したことにより、対象座標へ配置不可能にならないかを確認する関数を返す """ def queen_filter(new_point): return new_point[0] != queen_point[0] and \ new_point[1] != queen_point[1] and \ new_point[1] != new_point[0] + queen_point[1] - queen_point[0] and \ new_point[1] != -new_point[0] + queen_point[1] + queen_point[0] return queen_filter def get_board_string(queen_points): """ クイーンの位置座標の配列を指定出力形式に変換する """ queen_points_set = set(list(map(lambda point: "{}:{}".format(point[0], point[1]), queen_points))) board_string_lines = [] for y in range(BOARD_SIZE_H): line = "" for x in range(BOARD_SIZE_W): if "{}:{}".format(x, y) in queen_points_set: line += "Q" else: line += "." board_string_lines.append(line) return "\n".join(board_string_lines) def get_all_queen_points(board, queen_points): if len(queen_points) >= 8: return queen_points elif not board: return [] for empty_point in board: new_queen_points = [empty_point] new_queen_points.extend(queen_points) new_queen_points = get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) if new_queen_points: return get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) def main(): inputStr = sys.stdin.read() lines = inputStr.split("\n") if len(lines) <= 1: lines = [] else: lines = lines[1:] queen_points = list(map(lambda line: list(map(int, line.split(" "))), lines)) board = [[i % BOARD_SIZE_W, i // BOARD_SIZE_H] for i in range(BOARD_SIZE_H * BOARD_SIZE_W)] for queen_point in queen_points: board = set_queen(board, queen_point) print(get_board_string(get_all_queen_points(board, queen_points))) if __name__ == '__main__': main()
s648388685
p02244
u466299927
1523961855
Python
Python3
py
Runtime Error
20
5628
2435
# -*- coding: utf-8 -*- import sys BOARD_SIZE_W = 8 BOARD_SIZE_H = 8 def set_queen(board, queen_point): """ クイーンを指定座標に配置した後、残りの配置可能な位置の配列を返す """ return filter(create_queen_filter(queen_point), board) def create_queen_filter(queen_point): """ 指定位置にクイーンを配置したことにより、対象座標へ配置不可能にならないかを確認する関数を返す """ def queen_filter(new_point): return new_point[1] != queen_point[1] and \ new_point[0] != queen_point[0] and \ new_point[0] != new_point[1] + queen_point[0] - queen_point[1] and \ new_point[0] != -new_point[1] + queen_point[0] + queen_point[1] return queen_filter def get_board_string(queen_points): """ クイーンの位置座標の配列を指定出力形式に変換する """ queen_points_set = set(list(map(lambda point: "{}:{}".format(point[1], point[0]), queen_points))) board_string_lines = [] for y in range(BOARD_SIZE_H): line = "" for x in range(BOARD_SIZE_W): if "{}:{}".format(x, y) in queen_points_set: line += "Q" else: line += "." board_string_lines.append(line) return "\n".join(board_string_lines) def get_all_queen_points(board, queen_points): if len(queen_points) >= 8: return queen_points elif not board: return [] for empty_point in board: new_queen_points = [empty_point] new_queen_points.extend(queen_points) new_queen_points = get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) if new_queen_points: return get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) def main(): inputStr = sys.stdin.read() lines = inputStr.split("\n") lines = list(filter(lambda line: line, lines)) if len(lines) <= 1: lines = [] else: lines = lines[1:] queen_points = list(map(lambda line: list(map(int, line.split(" "))), lines)) board = [[i % BOARD_SIZE_W, i // BOARD_SIZE_H] for i in range(BOARD_SIZE_H * BOARD_SIZE_W)] for queen_point in queen_points: board = set_queen(board, queen_point) print(get_board_string(get_all_queen_points(board, queen_points))) if __name__ == '__main__': main()
s962900907
p02244
u466299927
1523961972
Python
Python3
py
Runtime Error
20
5628
2435
# -*- coding: utf-8 -*- import sys BOARD_SIZE_W = 8 BOARD_SIZE_H = 8 def set_queen(board, queen_point): """ クイーンを指定座標に配置した後、残りの配置可能な位置の配列を返す """ return filter(create_queen_filter(queen_point), board) def create_queen_filter(queen_point): """ 指定位置にクイーンを配置したことにより、対象座標へ配置不可能にならないかを確認する関数を返す """ def queen_filter(new_point): return new_point[1] != queen_point[1] and \ new_point[0] != queen_point[0] and \ new_point[0] != new_point[1] + queen_point[0] - queen_point[1] and \ new_point[0] != -new_point[1] + queen_point[0] + queen_point[1] return queen_filter def get_board_string(queen_points): """ クイーンの位置座標の配列を指定出力形式に変換する """ queen_points_set = set(list(map(lambda point: "{}:{}".format(point[1], point[0]), queen_points))) board_string_lines = [] for y in range(BOARD_SIZE_H): line = "" for x in range(BOARD_SIZE_W): if "{}:{}".format(x, y) in queen_points_set: line += "Q" else: line += "." board_string_lines.append(line) return "\n".join(board_string_lines) def get_all_queen_points(board, queen_points): if len(queen_points) >= 8: return queen_points elif not board: return [] for empty_point in board: new_queen_points = [empty_point] new_queen_points.extend(queen_points) new_queen_points = get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) if new_queen_points: return get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) def main(): inputStr = sys.stdin.read() lines = inputStr.split("\n") lines = list(filter(lambda line: line, lines)) if len(lines) <= 1: lines = [] else: lines = lines[1:] queen_points = list(map(lambda line: list(map(int, line.split(" "))), lines)) board = [[i % BOARD_SIZE_W, i // BOARD_SIZE_H] for i in range(BOARD_SIZE_H * BOARD_SIZE_W)] for queen_point in queen_points: board = set_queen(board, queen_point) print(get_board_string(get_all_queen_points(board, queen_points))) if __name__ == '__main__': main()
s336920426
p02244
u466299927
1523962368
Python
Python3
py
Runtime Error
20
5628
2453
# -*- coding: utf-8 -*- import sys BOARD_SIZE_W = 8 BOARD_SIZE_H = 8 def set_queen(board, queen_point): """ クイーンを指定座標に配置した後、残りの配置可能な位置の配列を返す """ return filter(create_queen_filter(queen_point), board) def create_queen_filter(queen_point): """ 指定位置にクイーンを配置したことにより、対象座標へ配置不可能にならないかを確認する関数を返す """ def queen_filter(new_point): return new_point[1] != queen_point[1] and \ new_point[0] != queen_point[0] and \ new_point[0] != new_point[1] + queen_point[0] - queen_point[1] and \ new_point[0] != -new_point[1] + queen_point[0] + queen_point[1] return queen_filter def get_board_string(queen_points): """ クイーンの位置座標の配列を指定出力形式に変換する """ queen_points_set = set(list(map(lambda point: "{}:{}".format(point[1], point[0]), queen_points))) board_string_lines = [] for y in range(BOARD_SIZE_H): line = "" for x in range(BOARD_SIZE_W): if "{}:{}".format(x, y) in queen_points_set: line += "Q" else: line += "." board_string_lines.append(line) return "\n".join(board_string_lines) def get_all_queen_points(board, queen_points): if len(queen_points) >= 8: return queen_points elif not board: return [] for empty_point in board: new_queen_points = [empty_point] new_queen_points.extend(queen_points) new_queen_points = get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) if new_queen_points: return get_all_queen_points(list(set_queen(board, empty_point)), new_queen_points) def main(): inputStr = sys.stdin.read() lines = inputStr.split("\n") lines = list(filter(lambda line: line, lines)) if len(lines) <= 1: lines = [] else: lines = lines[1:] queen_points = list(map(lambda line: list(map(int, line.split(" "))), lines)) board = [[i % BOARD_SIZE_W, i // BOARD_SIZE_H] for i in range(BOARD_SIZE_H * BOARD_SIZE_W)] for queen_point in queen_points: board = set_queen(board, queen_point) sys.stdout.write(get_board_string(get_all_queen_points(board, queen_points)) + "\n") if __name__ == '__main__': main()
s718582803
p02244
u825008385
1526255091
Python
Python3
py
Runtime Error
0
0
5309
# 8 Puzzle import copy z = 0 [N, d] = [3, 0] check_flag = [[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], [2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1], [3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2], [4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3], [3, 2, 1, 4, 3, 2, 1, 4, 3, 2, 1, 4], [2, 1, 4, 3, 2, 1, 4, 3, 2, 1, 4, 3], [1, 4, 3, 2, 1, 4, 3, 2, 1, 4, 3, 2], [4, 3, 2, 1, 4, 3, 2, 1, 4, 3, 2, 1]] start = [] goal = [[i + j*N for i in range(1, N + 1)] for j in range(N)] goal[2][2] = 0 for i in range(N): start.append(list(map(int, input().split()))) def manhattan(value, pairs): h = 0 if value == 1: h = (pairs[0] + pairs[1]) if value == 2: h = (pairs[0] + abs(pairs[1] - 1)) if value == 3: h = (pairs[0] + abs(pairs[1] - 2)) if value == 4: h = (abs(pairs[0] - 1) + pairs[1]) if value == 5: h = (abs(pairs[0] - 1) + abs(pairs[1] - 1)) if value == 6: h = (abs(pairs[0] - 1) + abs(pairs[1] - 2)) if value == 7: h = (abs(pairs[0] - 2) + pairs[1]) if value == 8: h = (abs(pairs[0] - 2) + abs(pairs[1] - 1)) return h def flag_array(flag, input): flag.pop(0) flag.append(input) return flag s_h = 0 for i in range(N): for j in range(N): s_h += manhattan(start[i][j], [i, j]) # print(s_h) for i in range(N): check = start[i].count(0) if check != 0: [s_r, s_c] = [i, start[i].index(0)] break if i == 3: print("Error") while True: d += 1 queue = [] flag = [0 for i in range(12)] queue.append([s_h, start, 0, [s_r, s_c], flag]) #while True: while len(queue) != 0: #print("Q: ", len(queue), "depth: ", d) short_n = queue.pop(0) h = short_n[0] - short_n[2] state = short_n[1] g = short_n[2] [r, c] = short_n[3] flag = short_n[4] #print("left_Q: ", len(queue), "depth: ", d, "h: ", h, "g: ", g, "state: ", state, "g+h: ", short_n[0], "flag: ", flag[len(flag) - 1]) #print("left_Q: ", len(queue), "depth: ", d, "h: ", h, "g: ", g, "flag: ", flag, "g+h: ", short_n[0]) #if d == 1: #print(short_n[0]) #print(state) #print(g) if h == 0: print(short_n[2]) #print(z) break """ if flag in check_flag: z += 1 continue """ if r - 1 >= 0 and flag[len(flag) - 1] != 3: [temp, temp_array] = [copy.deepcopy(state), flag[:]] h = short_n[0] - short_n[2] - manhattan(temp[r - 1][c], [r - 1, c]) + manhattan(temp[r - 1][c], [r, c]) [temp[r][c], temp[r - 1][c]] = [temp[r - 1][c], temp[r][c]] #if temp[r][c] != goal[r][c]: #[r, c] = [r - 1, c] #if temp #h = manhattan(temp) #print("1: ", h, temp) if g + 1 + h <= d: queue.append([h + g + 1, temp, g + 1, [r - 1, c], flag_array(temp_array, 1)]) if c + 1 < N and flag[len(flag) - 1] != 4: #print("2: ") [temp, temp_array] = [copy.deepcopy(state), flag[:]] #temp_array = copy.deepcopy(flag) h = short_n[0] - short_n[2] - manhattan(temp[r][c + 1], [r, c + 1]) + manhattan(temp[r][c + 1], [r, c]) [temp[r][c], temp[r][c + 1]] = [temp[r][c + 1], temp[r][c]] #queue.append(calculate(temp, g + 1)) #print("2: ", h, temp) if g + 1 + h <= d: queue.append([h + g + 1, temp, g + 1, [r, c + 1], flag_array(temp_array, 2)]) if r + 1 < N and flag[len(flag) - 1] != 1: #print("3: ") [temp, temp_array] = [copy.deepcopy(state), flag[:]] #temp_array = copy.deepcopy(flag) h = short_n[0] - short_n[2] - manhattan(temp[r + 1][c], [r + 1, c]) + manhattan(temp[r + 1][c], [r, c]) [temp[r][c], temp[r + 1][c]] = [temp[r + 1][c], temp[r][c]] #queue.append(calculate(temp, g + 1)) #print("3: ", h, temp) if g + 1 + h <= d: queue.append([h + g + 1, temp, g + 1, [r + 1, c], flag_array(temp_array, 3)]) if c - 1 >= 0 and flag[len(flag) - 1] != 2: #print("4: ") [temp, temp_array] = [copy.deepcopy(state), flag[:]] h = short_n[0] - short_n[2] - manhattan(temp[r][c - 1], [r, c - 1]) + manhattan(temp[r][c - 1], [r, c]) [temp[r][c], temp[r][c - 1]] = [temp[r][c - 1], temp[r][c]] if g + 1 + h <= d: queue.append([h + g + 1, temp, g + 1, [r, c - 1], flag_array(temp_array, 4)]) queue.sort(key = lambda data:data[0]) queue.sort(key = lambda data:data[2], reverse = True) data = [] g_data = [] #print(queue) """ for i in range(len(queue)): data.append(str(queue[i][0])) g_data.append(str(queue[i][2])) #print(queue[i]) print("g+h: ",' '.join(data)) print("g: ",' '.join(g_data)) """ #if d == 1: #print(len(queue)) if state == goal: break
s728374083
p02244
u138546245
1526779475
Python
Python3
py
Runtime Error
0
0
2100
from copy import deepcopy class EightQueen: NQUEENS = 8 SIZE = 8 class Board: def __init__(self, size): self.queens = [] self.size = size def place(self, i, j): self.queens.append((i, j)) def count(self): return len(self.queens) def ok(self, i, j): for qi, qj in self.queens: if qi == i: return False if qj == j: return False if i - j == qi - qj: return False if i + j == qi + qj: return False return True def __str__(self): s = '' for i in range(self.size): for j in range(self.size): if (i, j) in self.queens: s += "Q" else: s += "." s += '\n' return s def __init__(self): self.board = self.Board(self.SIZE) def add_queen(self, i, j): self.board.place(i, j) def solve(self): def _solve(board, si, sj): if board.count() == self.NQUEENS: return board for i, j in _from_pos(si, sj): if board.ok(i, j): b = deepcopy(board) b.place(i, j) result = _solve(b, i, j) if result is not None: return result else: return None def _from_pos(i, j): for n in range(i*self.SIZE + j, self.SIZE*self.SIZE): yield (n // self.SIZE, n % self.SIZE) self.board = _solve(self.board, 0, 0) def __str__(self): if self.board is None: return 'no solution' else: return str(self.board) def run(): input() q = EightQueen() for i, j in [int(i) for i in input().split()]: q.add_queen(i, j) q.solve() print(q) if __name__ == '__main__': run()
s088353908
p02245
u800534567
1545537640
Python
Python3
py
Runtime Error
0
0
2347
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> typedef char Board[10]; Board ini_board, board; const Board target = "123456780"; Board *history; int nhistories=0; typedef enum { U, D, L, R } Direction; typedef struct { int pos; Direction dir; } Motion; int minstep = INT_MAX; const Motion candidate[9][5] = {{{1,L},{3,U},{-1}}, {{0,R},{2,L},{4,U},{-1}}, {{1,R},{5,U},{-1}}, {{0,D},{4,L},{6,U},{-1}}, {{1,D},{5,L},{7,U},{3,R},{-1}}, {{2,D},{8,U},{4,R},{-1}}, {{3,D},{7,L},{-1}}, {{4,D},{8,L},{6,R},{-1}}, {{5,D},{7,R},{-1}} }; int move(Motion m) { if (m.pos==0 && board[0]=='1') return -1; if ((m.pos==1||m.pos==2) && board[0]=='1'&&board[1]=='2'&&board[2]=='3') return -1; switch (m.dir) { case U: if (m.pos<3) return -1; board[m.pos-3] = board[m.pos]; break; case D: if (m.pos>5) return -1; board[m.pos+3] = board[m.pos]; break; case L: if (m.pos%3==0) return -1; board[m.pos-1] = board[m.pos]; break; case R: if (m.pos%3==2) return -1; board[m.pos+1] = board[m.pos]; break; } board[m.pos] = '0'; return m.pos; } void search_path(int step, int space) { int i, j; if (strcmp(board, "123456780")==0) { // printf("STEP=%d\n", step); if (step==1) { printf("1\n"); exit(0); } if (step<minstep) minstep=step; } else { int s2; if (step>=minstep) return; if (step>0 && strcmp(board, ini_board)==0) return; Board board_bak; strcpy(board_bak, board); int nhistories_bak=nhistories; for (i=0; candidate[space][i].pos>=0; i++) { if ((s2 = move(candidate[space][i]))<0) continue; for (j=0; j<nhistories; j++) { if (strcmp(board, history[j])==0) break; } if (j==nhistories) { strcpy(history[nhistories++], board); search_path(step+1, s2); } nhistories = nhistories_bak; strcpy(board, board_bak); } } } int main() { fscanf(stdin, "%c %c %c\n", &board[0],&board[1],&board[2]); fscanf(stdin, "%c %c %c\n", &board[3],&board[4],&board[5]); fscanf(stdin, "%c %c %c\n", &board[6],&board[7],&board[8]); strcpy(ini_board, board); int space = strchr(board, '0')-board; history = (Board*)malloc(sizeof(Board)*100000); search_path(0, space); printf("%d\n", minstep); return 0; }
s636136411
p02245
u800534567
1545546390
Python
Python3
py
Runtime Error
0
0
2311
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> typedef char Board[10]; Board ini_board, board; const Board target = "123456780"; Board *history; int nhistories=0; typedef enum { U, D, L, R } Direction; typedef struct { int pos; Direction dir; } Motion; int minstep = 50; const Motion candidate[9][5] = {{{1,L},{3,U},{-1}}, {{0,R},{2,L},{4,U},{-1}}, {{1,R},{5,U},{-1}}, {{0,D},{4,L},{6,U},{-1}}, {{1,D},{5,L},{7,U},{3,R},{-1}}, {{2,D},{8,U},{4,R},{-1}}, {{3,D},{7,L},{-1}}, {{4,D},{8,L},{6,R},{-1}}, {{5,D},{7,R},{-1}} }; int move(Motion m) { if (m.pos==0 && board[0]=='1') return -1; if ((m.pos==1||m.pos==2) && board[0]=='1'&&board[1]=='2'&&board[2]=='3') return -1; switch (m.dir) { case U: if (m.pos<3) return -1; board[m.pos-3] = board[m.pos]; break; case D: if (m.pos>5) return -1; board[m.pos+3] = board[m.pos]; break; case L: if (m.pos%3==0) return -1; board[m.pos-1] = board[m.pos]; break; case R: if (m.pos%3==2) return -1; board[m.pos+1] = board[m.pos]; break; } board[m.pos] = '0'; return m.pos; } void search_path(int step, int space) { int i, j, s2; if (strcmp(board, "123456780")==0) { if (step==1) { printf("1\n"); exit(0); } if (step<minstep) minstep=step; } else { if (step>=minstep) return; if (step>0 && strcmp(board, ini_board)==0) return; Board board_bak; strcpy(board_bak, board); int nhistories_bak=nhistories; for (i=0; candidate[space][i].pos>=0; i++) { if ((s2 = move(candidate[space][i]))<0) continue; for (j=0; j<nhistories; j++) { if (strcmp(board, history[j])==0) // 前と同じ配置になったので次の手を試す break; } if (j==nhistories) { strcpy(history[nhistories++], board); search_path(step+1, s2); } nhistories = nhistories_bak; strcpy(board, board_bak); } } } int main() { fscanf(stdin, "%c %c %c\n", &board[0],&board[1],&board[2]); fscanf(stdin, "%c %c %c\n", &board[3],&board[4],&board[5]); fscanf(stdin, "%c %c %c\n", &board[6],&board[7],&board[8]); strcpy(ini_board, board); history = (Board*)malloc(sizeof(Board)*10000); search_path(0, strchr(board, '0')-board); printf("%d\n", minstep); return 0; }
s340273741
p02245
u800534567
1545632670
Python
Python3
py
Runtime Error
0
0
818
import sys import queue N = 3 f= ''.join(sys.stdin.readline().split()) f+= ''.join(sys.stdin.readline().split()) f+= ''.join(sys.stdin.readline().split()) dd = [[-1, 0], [0, -1], [1, 0], [0, 1]] Q = queue.Queue() V = dict() Q.put([f,f.index('0'),0]) V[f] = True while not Q.empty(): u = Q.get() if u[0] == '123456780': break sx, sy = u[1]//N, u[1]%N for dx, dy in dd: tx, ty = sx+dx, sy+dy if tx<0 or ty<0 or tx>=N or ty>=N: continue v = u[:] n1, n2 = u[1], tx*N+ty v[1] = n2 if n1>n2: n1, n2 = n2, n1 v[0] = v[0][0:n1]+v[0][n2]+v[0][n1+1:n2]+v[0][n1]+v[0][n2+1:] if not V.get(v[0], False): V[v[0]] = True v[2] += 1 # dir[r] Q.put(v) print(u[2])
s432588145
p02245
u800534567
1545632682
Python
Python3
py
Runtime Error
0
0
818
import sys import queue N = 3 f= ''.join(sys.stdin.readline().split()) f+= ''.join(sys.stdin.readline().split()) f+= ''.join(sys.stdin.readline().split()) dd = [[-1, 0], [0, -1], [1, 0], [0, 1]] Q = queue.Queue() V = dict() Q.put([f,f.index('0'),0]) V[f] = True while not Q.empty(): u = Q.get() if u[0] == '123456780': break sx, sy = u[1]//N, u[1]%N for dx, dy in dd: tx, ty = sx+dx, sy+dy if tx<0 or ty<0 or tx>=N or ty>=N: continue v = u[:] n1, n2 = u[1], tx*N+ty v[1] = n2 if n1>n2: n1, n2 = n2, n1 v[0] = v[0][0:n1]+v[0][n2]+v[0][n1+1:n2]+v[0][n1]+v[0][n2+1:] if not V.get(v[0], False): V[v[0]] = True v[2] += 1 # dir[r] Q.put(v) print(u[2])
s931781703
p02245
u800534567
1545632778
Python
Python3
py
Runtime Error
0
0
817
import sys import queue N = 3 f= ''.join(sys.stdin.readline().split()) f+= ''.join(sys.stdin.readline().split()) f+= ''.join(sys.stdin.readline().split()) dd = [[-1, 0], [0, -1], [1, 0], [0, 1]] Q = queue.Queue() V = dict() Q.put([f,f.index('0'),0]) V[f] = True while not Q.empty(): u = Q.get() if u[0] == '123456780': break sx, sy = u[1]//N, u[1]%N for dx, dy in dd: tx, ty = sx+dx, sy+dy if tx<0 or ty<0 or tx>=N or ty>=N: continue v = u[:] n1, n2 = u[1], tx*N+ty v[1] = n2 if n1>n2: n1, n2 = n2, n1 v[0] = v[0][0:n1]+v[0][n2]+v[0][n1+1:n2]+v[0][n1]+v[0][n2+1:] if not V.get(v[0], False): V[v[0]] = True v[2] += 1 # dir[r] Q.put(v) print(u[2])
s905547687
p02245
u800534567
1545651683
Python
Python3
py
Runtime Error
0
0
2557
#include <stdlib.h> #include <string.h> typedef char Board[10]; Board ini_board, board, *history; const Board target = "123456780"; int nhistories=0; typedef enum { U, D, L, R } Direction; typedef struct { char pos; char dir; } Motion; int minstep; const Motion motion[9][5] = {{{1,L},{3,U},{-1}}, {{0,R},{2,L},{4,U},{-1}}, {{1,R},{5,U},{-1}}, {{0,D},{4,L},{6,U},{-1}}, {{1,D},{5,L},{7,U},{3,R},{-1}}, {{2,D},{8,U},{4,R},{-1}}, {{3,D},{7,L},{-1}}, {{4,D},{8,L},{6,R},{-1}}, {{5,D},{7,R},{-1}} }; int search_path(int step, char space) { int i, j; if (strcmp(board, "123456780")==0) { // printf("STEP=%d\n", step); //printf("%d\n", step); if (step<minstep) minstep=step; printf("%d\n", step); exit(0); } else { if (step>=minstep) return 1; if (step>0 && strcmp(board, ini_board)==0) return 1; Board board_bak; strcpy(board_bak, board); int nhistories_bak=nhistories; for (i=0; motion[space][i].pos>=0; i++) { Motion m = motion[space][i]; if (m.pos==0 && board[0]=='1') continue; if ((m.pos==1||m.pos==2) && board[0]=='1'&&board[1]=='2'&&board[2]=='3') conti\ nue; if ((m.pos==3||m.pos==6) && board[0]=='1'&&board[3]=='4'&&board[6]=='7')contin\ ue; switch (m.dir) { case U: if (m.pos<3) continue; board[m.pos-3] = board[m.pos]; break; case D: if (m.pos>5) continue; board[m.pos+3] = board[m.pos]; break; case L: if (m.pos%3==0) continue; board[m.pos-1] = board[m.pos]; break; case R: if (m.pos%3==2) continue; board[m.pos+1] = board[m.pos]; break; } board[m.pos] = '0'; for (j=0; j<nhistories; j++) { if (strcmp(board, history[j])==0) break; } if (j==nhistories) { strcpy(history[nhistories++], board); search_path(step+1, m.pos); } nhistories = nhistories_bak; strcpy(board, board_bak); } } return 1; } int main() { fscanf(stdin, "%c %c %c\n", &board[0],&board[1],&board[2]); fscanf(stdin, "%c %c %c\n", &board[3],&board[4],&board[5]); fscanf(stdin, "%c %c %c\n", &board[6],&board[7],&board[8]); strcpy(ini_board, board); for (minstep=1; minstep<32; minstep++) { strcpy(board, ini_board); history = (Board*)malloc(sizeof(Board)*100000); search_path(0, strchr(board, '0')-board); free(history); } return 0; }
s388193086
p02245
u800534567
1545651709
Python
Python3
py
Runtime Error
0
0
2576
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef char Board[10]; Board ini_board, board, *history; const Board target = "123456780"; int nhistories=0; typedef enum { U, D, L, R } Direction; typedef struct { char pos; char dir; } Motion; int minstep; const Motion motion[9][5] = {{{1,L},{3,U},{-1}}, {{0,R},{2,L},{4,U},{-1}}, {{1,R},{5,U},{-1}}, {{0,D},{4,L},{6,U},{-1}}, {{1,D},{5,L},{7,U},{3,R},{-1}}, {{2,D},{8,U},{4,R},{-1}}, {{3,D},{7,L},{-1}}, {{4,D},{8,L},{6,R},{-1}}, {{5,D},{7,R},{-1}} }; int search_path(int step, char space) { int i, j; if (strcmp(board, "123456780")==0) { // printf("STEP=%d\n", step); //printf("%d\n", step); if (step<minstep) minstep=step; printf("%d\n", step); exit(0); } else { if (step>=minstep) return 1; if (step>0 && strcmp(board, ini_board)==0) return 1; Board board_bak; strcpy(board_bak, board); int nhistories_bak=nhistories; for (i=0; motion[space][i].pos>=0; i++) { Motion m = motion[space][i]; if (m.pos==0 && board[0]=='1') continue; if ((m.pos==1||m.pos==2) && board[0]=='1'&&board[1]=='2'&&board[2]=='3') conti\ nue; if ((m.pos==3||m.pos==6) && board[0]=='1'&&board[3]=='4'&&board[6]=='7')contin\ ue; switch (m.dir) { case U: if (m.pos<3) continue; board[m.pos-3] = board[m.pos]; break; case D: if (m.pos>5) continue; board[m.pos+3] = board[m.pos]; break; case L: if (m.pos%3==0) continue; board[m.pos-1] = board[m.pos]; break; case R: if (m.pos%3==2) continue; board[m.pos+1] = board[m.pos]; break; } board[m.pos] = '0'; for (j=0; j<nhistories; j++) { if (strcmp(board, history[j])==0) break; } if (j==nhistories) { strcpy(history[nhistories++], board); search_path(step+1, m.pos); } nhistories = nhistories_bak; strcpy(board, board_bak); } } return 1; } int main() { fscanf(stdin, "%c %c %c\n", &board[0],&board[1],&board[2]); fscanf(stdin, "%c %c %c\n", &board[3],&board[4],&board[5]); fscanf(stdin, "%c %c %c\n", &board[6],&board[7],&board[8]); strcpy(ini_board, board); for (minstep=1; minstep<32; minstep++) { strcpy(board, ini_board); history = (Board*)malloc(sizeof(Board)*100000); search_path(0, strchr(board, '0')-board); free(history); } return 0; }
s339241182
p02245
u800534567
1545797180
Python
Python3
py
Runtime Error
0
0
1944
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { unsigned int b; char step; } Board; int qlen=32202; typedef enum { U, D, L, R } Direction; typedef struct { int pos; Direction dir; } Motion; const Motion motion[9][5] = {{{1,L},{3,U},{-1}}, {{0,R},{2,L},{4,U},{-1}}, {{1,R},{5,U},{-1}}, {{0,D},{4,L},{6,U},{-1}}, {{1,D},{5,L},{7,U},{3,R},{-1}}, {{2,D},{8,U},{4,R},{-1}}, {{3,D},{7,L},{-1}}, {{4,D},{8,L},{6,R},{-1}}, {{5,D},{7,R},{-1}} }; int findzero(unsigned int b) { for (int i=0; i<9; i++) { if (b%10==0) return 8-i; b/=10; } return -1; } unsigned int sq[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,1000000000 }; #define HISTLEN 8765432 int main() { int i, j, k; int qhead, qtail; qhead = qtail = 0; Board board; fscanf(stdin, "%d %d %d\n", &i, &j, &k); board.b = i*sq[8]+j*sq[7]+k*sq[6]; fscanf(stdin, "%d %d %d\n", &i, &j, &k); board.b += i*sq[5]+j*sq[4]+k*sq[3]; fscanf(stdin, "%d %d %d\n", &i, &j, &k); board.b += i*100+j*10+k; short int *used = (short int*)malloc(sizeof(short int)*HISTLEN); for (i=0; i<HISTLEN; i++) used[i]=0; Board *Q = (Board*)malloc(sizeof(Board)*qlen); board.step=0; Q[qhead++] = board; while (qhead>qtail) { board = Q[qtail++ %qlen]; if (board.b==123456780) break; int space = findzero(board.b); for (i=0; motion[space][i].pos>=0; i++) { Board b = board; Motion m = motion[space][i]; if (m.pos==0 && b.b/sq[8]==1) continue; if ((m.pos==1||m.pos==2) && b.b/sq[8]==1&&(b.b%sq[8])/sq[7]==2&&(b.b%sq[7])/sq[6]==3) continue; int nn=b.b%sq[8-m.pos+1]/sq[8-m.pos]; b.b = nn*sq[8-space]+b.b-nn*sq[8-m.pos]; b.step = board.step+1; k=b.b/100; if ((used[k] & (1<<(b.b%10)))==(1<<(b.b%10))) continue; used[k] |= (1<<(board.b%10)); Q[qhead++ %qlen] = b; } } printf("%d\n", board.step); return 0; }
s872201964
p02245
u797673668
1455093407
Python
Python3
py
Runtime Error
880
24560
1010
import heapq from itertools import chain from operator import mul exp10 = [10 ** a for a in range(8, -1, -1)] movables = [{1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7}] destination = 123456780 def swap(board, move_from, move_to): return board + (exp10[move_to] - exp10[move_from]) * (board // exp10[move_from] % 10) board0 = sum(map(mul, exp10, chain.from_iterable(map(int, input().split()) for _ in range(3)))) p0 = str(board0).index('0') appeared = {board0} queue = list((0, move_from, p0, board0) for move_from in movables[p0]) heapq.heapify(queue) while True: total_cost, move_from, move_to, board = heapq.heappop(queue) if board == destination: print(total_cost) break new_board = swap(board, move_from, move_to) if new_board in appeared: continue for move_from2 in movables[move_from]: if move_from2 != move_to: heapq.heappush(queue, (total_cost + 1, move_from2, move_from, new_board))
s183831576
p02245
u024715419
1513043488
Python
Python3
py
Runtime Error
0
0
2415
import heapq def d_manhattan(node_list): s = 0 for i in range(9): x_goal = i%3 y_goal = i//3 x_now = (node_list[i] - 1)%3 y_now = (node_list[i] - 1)//3 if y_now == -1: y_now = 2 dx = abs(x_now - x_goal) dy = abs(y_now - y_goal) s += dx + dy return s def moveNodeE(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space + 1] = node_tmp[space + 1], node_tmp[space] return node_tmp def moveNodeW(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space - 1] = node_tmp[space - 1], node_tmp[space] return node_tmp def moveNodeN(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space - 3] = node_tmp[space - 3], node_tmp[space] return node_tmp def moveNodeS(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space + 3] = node_tmp[space + 3], node_tmp[space] return node_tmp class board: def __init__(self, node_list, g): self.node = node_list self.space = node_list.index(0) self.g = g self.h = d_manhattan(node_list) self.f = self.g + self.h def makeBoard(self): space = self.space cost_now = self.f x_s = space%3 y_s = space//3 if x_s < 2: node_tmp = moveNodeE(self.node, space) yield board(node_tmp, self.g + 1) if x_s > 0: node_tmp = moveNodeW(self.node, space) yield board(node_tmp, self.g + 1) if y_s < 2: node_tmp = moveNodeS(self.node, space) yield board(node_tmp, self.g + 1) if y_s > 0: node_tmp = moveNodeN(self.node, space) yield board(node_tmp, self.g + 1) b_open = [] n_close = {} n_goal = [1,2,3,4,5,6,7,8,0] n_start = [] for i in range(3): inp = list(map(int, raw_input().split())) n_start.extend(inp) b_start = board(n_start, 0) heapq.heappush(b_open, (b_start.f, b_start.h, 0, b_start)) i = 0 while b_open: _, _, _, b_now = heapq.heappop(b_open) if b_now.node == n_goal: b_goal = b_now break n_close["".join(map(str, b_now.node))] = i for b_new in b_now.makeBoard(): if "".join(map(str, b_new.node)) in n_close: continue heapq.heappush(b_open, (b_new.f, b_new.h, i, b_new)) i += 1 print(b_goal.g)
s837433173
p02245
u024715419
1513043549
Python
Python3
py
Runtime Error
0
0
2415
import heapq def d_manhattan(node_list): s = 0 for i in range(9): x_goal = i%3 y_goal = i//3 x_now = (node_list[i] - 1)%3 y_now = (node_list[i] - 1)//3 if y_now == -1: y_now = 2 dx = abs(x_now - x_goal) dy = abs(y_now - y_goal) s += dx + dy return s def moveNodeE(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space + 1] = node_tmp[space + 1], node_tmp[space] return node_tmp def moveNodeW(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space - 1] = node_tmp[space - 1], node_tmp[space] return node_tmp def moveNodeN(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space - 3] = node_tmp[space - 3], node_tmp[space] return node_tmp def moveNodeS(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space + 3] = node_tmp[space + 3], node_tmp[space] return node_tmp class board: def __init__(self, node_list, g): self.node = node_list self.space = node_list.index(0) self.g = g self.h = d_manhattan(node_list) self.f = self.g + self.h def makeBoard(self): space = self.space cost_now = self.f x_s = space%3 y_s = space//3 if x_s < 2: node_tmp = moveNodeE(self.node, space) yield board(node_tmp, self.g + 1) if x_s > 0: node_tmp = moveNodeW(self.node, space) yield board(node_tmp, self.g + 1) if y_s < 2: node_tmp = moveNodeS(self.node, space) yield board(node_tmp, self.g + 1) if y_s > 0: node_tmp = moveNodeN(self.node, space) yield board(node_tmp, self.g + 1) b_open = [] n_close = {} n_goal = [1,2,3,4,5,6,7,8,0] n_start = [] for i in range(3): inp = list(map(int, raw_input().split())) n_start.extend(inp) b_start = board(n_start, 0) heapq.heappush(b_open, (b_start.f, b_start.h, 0, b_start)) i = 0 while b_open: _, _, _, b_now = heapq.heappop(b_open) if b_now.node == n_goal: b_goal = b_now break n_close["".join(map(str, b_now.node))] = i for b_new in b_now.makeBoard(): if "".join(map(str, b_new.node)) in n_close: continue heapq.heappush(b_open, (b_new.f, b_new.h, i, b_new)) i += 1 print(b_goal.g)
s240908239
p02245
u426534722
1519743939
Python
Python3
py
Runtime Error
0
0
818
from collections import deque dy = [-1, 0, 0, 1] dx = [0, -1, 1, 0] def g(i, j, a): t = a // (10 ** j) % 10 return a - t * (10 ** j) + t * (10 ** i) def MAIN(): m = {8:{7, 5}, 7:{8, 6, 4}, 6:{7, 3}, 5:{8, 4, 2}, 4:{7, 5, 3, 1}, 3:{6, 4, 0}, 2:{5, 1}, 1:{4, 2, 0}, 0:{3, 1}} MAP = "".join(input().replace(" ", "") for _ in range(N)) start = 8 - MAP.find("0") MAP = int(MAP) goal = ('1', '2', '3', '4', '5', '6', '7', '8', '0') goal = 123456780 dp = deque([(0, start, MAP)]) LOG = {MAP} while dp: cnt, yx, M = dp.popleft() if M == goal: print(cnt) break cnt += 1 for nyx in m[yx]: CM = g(yx, nyx, M) if not CM in LOG: dp.append((cnt, nyx, CM)) LOG.add(CM) MAIN()
s905230411
p02245
u620516796
1524439520
Python
Python3
py
Runtime Error
0
0
5981
import time import math class Node: def __init__(self, board, parent, fValue, depth): self.board = board self.parent = parent self.fValue = fValue self.depth = depth def __eq__(self, other): return self.board == other.board def __lt__(self, other): return self.fValue < other.fValue def __hash__(self): return hash(self.board) def __bool__(self): return True class Board: # The 8-puzzle board representation # def __init__(self, matrix): self.matrix = matrix for i in range(len(matrix)): if 0 in matrix[i]: self.blankPos = (i, matrix[i].index(0)) def __str__(self): s = "" for i in range(len(self.matrix)): s += str(self.matrix[i]) + "\n" return s + "\n" def __eq__(self, other): otherMatrix = other.matrix thisMatrix = self.matrix if len(thisMatrix) != len(otherMatrix): return False for i in range(len(thisMatrix)): if len(thisMatrix[i]) != len(otherMatrix[i]): return False for j in range(len(thisMatrix[i])): if thisMatrix[i][j] != otherMatrix[i][j]: return False return True def duplicate(self): newMatrix = [] for i in range(len(self.matrix)): newMatrix.append([]) for j in range(len(self.matrix[i])): newMatrix[i].append(self.matrix[i][j]) return Board(newMatrix) def findElement(self, elem): for i in range(len(self.matrix)): for j in range(len(self.matrix[i])): if self.matrix[i][j] == elem: return (i, j) return None def slideBlank(self, dir): # dir is a tuple (deltaY,deltaX) if dir not in [(0, 1), (0, -1), (-1, 0), (1, 0)]: raise ValueError("Invalid dir") newBlankPos = (self.blankPos[0] + dir[0], self.blankPos[1] + dir[1]) if newBlankPos[0] < 0 or newBlankPos[0] > len(self.matrix) - 1: return None elif newBlankPos[1] < 0 or newBlankPos[1] > len(self.matrix[0]) - 1: return None else: newBoard = self.duplicate() saveVal = newBoard.matrix[self.blankPos[0] + dir[0]][self.blankPos[1] + dir[1]] newBoard.matrix[self.blankPos[0] + dir[0]][self.blankPos[1] + dir[1]] = 0 newBoard.matrix[self.blankPos[0]][self.blankPos[1]] = saveVal newBoard.blankPos = (self.blankPos[0] + dir[0], self.blankPos[1] + dir[1]) return newBoard def __hash__(self): s = 0 for i in range(len(self.matrix)): for j in range(len(self.matrix[i])): s *= 10 s += self.matrix[i][j] return s def fastSearch(frontier, goalBoard, explored): curNode = frontier.pop(0) explored.add(curNode) if curNode.board == goalBoard: print(curNode.depth) return True aStarExpansion(curNode, frontier, goalBoard, explored) return False def fastSearchClient(board, goalBoard): frontier = [Node(board, None, heuristic(board, goalBoard), 0)] explored = set() limit = 0 while (limit < 1000): retval = fastSearch(frontier, goalBoard, explored) if retval: return limit += 1 return # Function to expand the frontier using aStar # def aStarExpansion(currentNode, frontier, goalBoard, explored): sideLength = len(currentNode.board.matrix) pos = currentNode.board.blankPos depth = currentNode.depth + 1 toInsert = [] # if we can move there, make a node and put it in toInsert if pos[0] != 0: upCost = depth + heuristic(currentNode.board.slideBlank((-1, 0)), goalBoard) upNode = Node(currentNode.board.slideBlank((-1, 0)), currentNode, upCost, depth) toInsert.append(upNode) if pos[0] != sideLength - 1: downCost = depth + heuristic(currentNode.board.slideBlank((1, 0)), goalBoard) downNode = Node(currentNode.board.slideBlank((1, 0)), currentNode, downCost, depth) toInsert.append(downNode) if pos[1] != 0: leftCost = depth + heuristic(currentNode.board.slideBlank((0, -1)), goalBoard) leftNode = Node(currentNode.board.slideBlank((0, -1)), currentNode, leftCost, depth) toInsert.append(leftNode) if pos[1] != sideLength - 1: rightCost = depth + heuristic(currentNode.board.slideBlank((0, 1)), goalBoard) rightNode = Node(currentNode.board.slideBlank((0, 1)), currentNode, rightCost, depth) toInsert.append(rightNode) # if we've already been there, we don't want to try that board again for node in explored: for insertNode in toInsert: if insertNode == node: toInsert.remove(insertNode) # now we are putting the nodes to be inserted into the correct place in frontier for node in toInsert: for i in range(len(frontier) + 1): if i == len(frontier): frontier.append(node) break if frontier[i] > node: frontier.insert(i, node) break def heuristic(currentBoard, goalBoard): currentMatrix = currentBoard.matrix sum = 0 for i in range(len(currentMatrix)): for j in range(len(currentMatrix[i])): cur = currentMatrix[i][j] if cur % 3 == 0: curx = 3 else: curx = cur % 3 if cur != 0: sum += abs(curx - (j + 1)) + abs(math.ceil(cur / 3) - (i + 1)) return sum arr = [[1 for i in range(3)] for j in range(3)] for i in range(3): arr[i][0], arr[i][1], arr[i][2] = raw_input().split() for i in range(3): for j in range(3): arr[i][j] = int(arr[i][j]) fastSearchClient(Board(arr), Board([[1, 2, 3], [4, 5, 6], [7, 8, 0]]))
s096609557
p02245
u620516796
1524439631
Python
Python3
py
Runtime Error
0
0
4757
import time import math class Node: def __init__(self, board, parent, fValue, depth): self.board = board self.parent = parent self.fValue = fValue self.depth = depth def __eq__(self, other): return self.board == other.board def __lt__(self, other): return self.fValue < other.fValue def __hash__(self): return hash(self.board) def __bool__(self): return True class Board: # The 8-puzzle board representation # def __init__(self, matrix): self.matrix = matrix for i in range(len(matrix)): if 0 in matrix[i]: self.blankPos = (i, matrix[i].index(0)) def __str__(self): s = "" for i in range(len(self.matrix)): s += str(self.matrix[i]) + "\n" return s + "\n" def __eq__(self, other): otherMatrix = other.matrix thisMatrix = self.matrix if len(thisMatrix) != len(otherMatrix): return False for i in range(len(thisMatrix)): if len(thisMatrix[i]) != len(otherMatrix[i]): return False for j in range(len(thisMatrix[i])): if thisMatrix[i][j] != otherMatrix[i][j]: return False return True def duplicate(self): newMatrix = [] for i in range(len(self.matrix)): newMatrix.append([]) for j in range(len(self.matrix[i])): newMatrix[i].append(self.matrix[i][j]) return Board(newMatrix) def findElement(self, elem): for i in range(len(self.matrix)): for j in range(len(self.matrix[i])): if self.matrix[i][j] == elem: return (i, j) return None def slideBlank(self, dir): # dir is a tuple (deltaY,deltaX) if dir not in [(0, 1), (0, -1), (-1, 0), (1, 0)]: raise ValueError("Invalid dir") newBlankPos = (self.blankPos[0] + dir[0], self.blankPos[1] + dir[1]) if newBlankPos[0] < 0 or newBlankPos[0] > len(self.matrix) - 1: return None elif newBlankPos[1] < 0 or newBlankPos[1] > len(self.matrix[0]) - 1: return None else: newBoard = self.duplicate() saveVal = newBoard.matrix[self.blankPos[0] + dir[0]][self.blankPos[1] + dir[1]] newBoard.matrix[self.blankPos[0] + dir[0]][self.blankPos[1] + dir[1]] = 0 newBoard.matrix[self.blankPos[0]][self.blankPos[1]] = saveVal newBoard.blankPos = (self.blankPos[0] + dir[0], self.blankPos[1] + dir[1]) return newBoard def __hash__(self): s = 0 for i in range(len(self.matrix)): for j in range(len(self.matrix[i])): s *= 10 s += self.matrix[i][j] return s def fastSearch(frontier, goalBoard, explored): curNode = frontier.pop(0) explored.add(curNode) if curNode.board == goalBoard: print(curNode.depth) return True aStarExpansion(curNode, frontier, goalBoard, explored) return False def fastSearchClient(board, goalBoard): frontier = [Node(board, None, heuristic(board, goalBoard), 0)] explored = set() limit = 0 while (limit < 1000): retval = fastSearch(frontier, goalBoard, explored) if retval: return limit += 1 return # Function to expand the frontier using aStar # def aStarExpansion(currentNode, frontier, goalBoard, explored): sideLength = len(currentNode.board.matrix) pos = currentNode.board.blankPos depth = currentNode.depth + 1 toInsert = [] # if we can move there, make a node and put it in toInsert if pos[0] != 0: upCost = depth + heuristic(currentNode.board.slideBlank((-1, 0)), goalBoard) upNode = Node(currentNode.board.slideBlank((-1, 0)), currentNode, upCost, depth) toInsert.append(upNode) if pos[0] != sideLength - 1: downCost = depth + heuristic(currentNode.board.slideBlank((1, 0)), goalBoard) downNode = Node(currentNode.board.slideBlank((1, 0)), currentNode, downCost, depth) toInsert.append(downNode) if pos[1] != 0: leftCost = depth + heuristic(currentNode.board.slideBlank((0, -1)), goalBoard) leftNode = Node(currentNode.board.slideBlank((0, -1)), currentNode, leftCost, depth) toInsert.append(leftNode) if pos[1] != sideLength - 1: rightCost = depth + heuristic(currentNode.board.slideBlank((0, 1)), goalBoard) rightNode = Node(currentNode.board.slideBlank((0, 1)), currentNode, rightCost, depth) toInsert.append(rightNode) # if we've already been there, we don't want to try that board again for node in explored: for insertNode in toInsert: if insertNode == node: toInsert.remove(insertNode) # now we are putting the nodes to be inserted into the correct place in frontier for node in toInsert: for i in range(len(frontier) + 1): if i == len(frontier): frontier.append(node) break if frontier[i] > node: frontier.insert(i, node) break def heuristic(currentBoard, goalBoard): currentMatrix = currentBoard.matrix sum = 0 for i in range(len(currentMatrix)): for j in range(len(currentMatrix[i])): cur = currentMatrix[i][j] if cur % 3 == 0: curx = 3 else: curx = cur % 3 if cur != 0: sum += abs(curx - (j + 1)) + abs(math.ceil(cur / 3) - (i + 1)) return sum arr = [[1 for i in range(3)] for j in range(3)] for i in range(3): arr[i][0], arr[i][1], arr[i][2] = input().split() for i in range(3): for j in range(3): arr[i][j] = int(arr[i][j]) fastSearchClient(Board(arr), Board([[1, 2, 3], [4, 5, 6], [7, 8, 0]]))
s990822004
p02245
u167493070
1525758807
Python
Python3
py
Runtime Error
0
0
2707
import sys; import heapq def iterative(i,j): q = [] heapq.heappush(q,(simpleHS(swap_puz),0,i,j,0,puz)) global finding while len(q): items = heapq.heappop(q) c_dWithH = items[0] c_depth = items[1] _i = items[2] _j = items[3] prev_move = items[4] c_puz = items[5] if(puzzleCheck(c_puz)): finding = 1 print(c_depth) break if((c_depth+c_dWithH) >= depth): continue if(_i != 0 and prev_move != 1): swap_puz = swapPuz(c_puz[0:],_i,_j,_i-1,_j) heapq.heappush(q,(c_depth+1+simpleHS(swap_puz),c_depth+1,_i-1,_j,2,swap_puz)) if(_i != 2 and prev_move != 2): swap_puz = swapPuz(c_puz[0:],_i,_j,_i+1,_j) heapq.heappush(q,(c_depth+1+simpleHS(swap_puz),c_depth+1,_i+1,_j,1,swap_puz)) if(_j != 0 and prev_move != 3): swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j-1) heapq.heappush(q,(c_depth+1+simpleHS(swap_puz),c_depth+1,_i,_j-1,4,swap_puz)) if(_j != 2 and prev_move != 4): swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j+1) heapq.heappush(q,(c_depth+1+simpleHS(swap_puz),c_depth+1,_i,_j+1,3,swap_puz)) def checkPuzIsExisted(puz,q): for i in range(len(q)): exist_puz = q[i][4] count = 0 for j in range(len(exist_puz)): if(exist_puz[j] != puz[j]): count = 1 if(count == 0): return True return False def sumCost(costs): value = 0 for i in range(len(costs)): value += costs[i] return value def simpleHS(c_puz): count = 0 for i in range(len(correctPuz)): if(correctPuz[i] != c_puz[i]): count+=1 return count def HS(i,j,num): k = correctPuz.index(num) ki = (int)(k/3) kj = k - ki*3 value = abs(_i-ki)+abs(_j-kj) return value def swapPuz(c_puz, i, j, i2,j2): c_puz[i2*3+j2],c_puz[i*3+j] = c_puz[i*3+j],c_puz[i2*3+j2] return c_puz def puzzleCheck(c_puz): if(c_puz[8] == 0): for i in range(len(correctPuz)): if(correctPuz[i] != c_puz[i]): return False return True return False correctPuz = [i+1 for i in range(9)] correctPuz[8] = 0 puz = [0 for i in range(9)] i_start = 0 j_start = 0 for i in range(3): puz[i*3],puz[i*3+1],puz[i*3+2] = map(int, input().split()); if(puz[i*3] == 0): i_start,j_start = i,0 elif(puz[i*3+1] == 0): i_start,j_start = i,1 elif(puz[i*3+2] == 0): i_start,j_start = i,2 finding = 0 depth = 0 while True: if(finding == 1): break iterative(i_start,j_start) depth+=1
s827927569
p02245
u167493070
1525758855
Python
Python3
py
Runtime Error
0
0
2707
import sys; import heapq def iterative(i,j): q = [] heapq.heappush(q,(simpleHS(swap_puz),0,i,j,0,puz)) global finding while len(q): items = heapq.heappop(q) c_dWithH = items[0] c_depth = items[1] _i = items[2] _j = items[3] prev_move = items[4] c_puz = items[5] if(puzzleCheck(c_puz)): finding = 1 print(c_depth) break if((c_depth+c_dWithH) >= depth): continue if(_i != 0 and prev_move != 1): swap_puz = swapPuz(c_puz[0:],_i,_j,_i-1,_j) heapq.heappush(q,(c_depth+1+simpleHS(swap_puz),c_depth+1,_i-1,_j,2,swap_puz)) if(_i != 2 and prev_move != 2): swap_puz = swapPuz(c_puz[0:],_i,_j,_i+1,_j) heapq.heappush(q,(c_depth+1+simpleHS(swap_puz),c_depth+1,_i+1,_j,1,swap_puz)) if(_j != 0 and prev_move != 3): swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j-1) heapq.heappush(q,(c_depth+1+simpleHS(swap_puz),c_depth+1,_i,_j-1,4,swap_puz)) if(_j != 2 and prev_move != 4): swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j+1) heapq.heappush(q,(c_depth+1+simpleHS(swap_puz),c_depth+1,_i,_j+1,3,swap_puz)) def checkPuzIsExisted(puz,q): for i in range(len(q)): exist_puz = q[i][4] count = 0 for j in range(len(exist_puz)): if(exist_puz[j] != puz[j]): count = 1 if(count == 0): return True return False def sumCost(costs): value = 0 for i in range(len(costs)): value += costs[i] return value def simpleHS(c_puz): count = 0 for i in range(len(correctPuz)): if(correctPuz[i] != c_puz[i]): count+=1 return count def HS(i,j,num): k = correctPuz.index(num) ki = (int)(k/3) kj = k - ki*3 value = abs(_i-ki)+abs(_j-kj) return value def swapPuz(c_puz, i, j, i2,j2): c_puz[i2*3+j2],c_puz[i*3+j] = c_puz[i*3+j],c_puz[i2*3+j2] return c_puz def puzzleCheck(c_puz): if(c_puz[8] == 0): for i in range(len(correctPuz)): if(correctPuz[i] != c_puz[i]): return False return True return False correctPuz = [i+1 for i in range(9)] correctPuz[8] = 0 puz = [0 for i in range(9)] i_start = 0 j_start = 0 for i in range(3): puz[i*3],puz[i*3+1],puz[i*3+2] = map(int, input().split()); if(puz[i*3] == 0): i_start,j_start = i,0 elif(puz[i*3+1] == 0): i_start,j_start = i,1 elif(puz[i*3+2] == 0): i_start,j_start = i,2 finding = 0 depth = 0 while True: if(finding == 1): break iterative(i_start,j_start) depth+=1
s143795036
p02245
u167493070
1525930062
Python
Python3
py
Runtime Error
0
0
2934
import sys; import heapq def iterative(i,j): q = [] q.append(sumcost,(0,i,j,0,puz)) global finding while len(q): c_dWithH, items = q.pop(0) c_depth = items[0] _i = items[1] _j = items[2] prev_move = items[3] c_puz = items[4] _sum_cost = c_dWithH - c_depth if(c_dWithH - c_depth == 0): finding = 1 print(c_depth) break if(c_dWithH > depth): continue c_cost = simpleHS(c_puz,_i,_j) print(c_depth) if(_i != 0 and prev_move != 1): swap_puz = swapPuz(c_puz[0:],_i,_j,_i-1,_j) q.append(c_depth+1+_sum_cost+checkCost(c_cost,simpleHS(c_puz,_i-1,_j),simpleHS(swap_puz,_i,_j),simpleHS(swap_puz,_i-1,_j)),(c_depth+1,_i-1,_j,2,swap_puz)) if(_i != 2 and prev_move != 2): swap_puz = swapPuz(c_puz[0:],_i,_j,_i+1,_j) q.append(c_depth+1+_sum_cost+checkCost(c_cost,simpleHS(c_puz,_i+1,_j),simpleHS(swap_puz,_i,_j),simpleHS(swap_puz,_i+1,_j)),(c_depth+1,_i+1,_j,1,swap_puz)) if(_j != 0 and prev_move != 3): swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j-1) q.append(c_depth+1+_sum_cost+checkCost(c_cost,simpleHS(c_puz,_i,_j-1),simpleHS(swap_puz,_i,_j),simpleHS(swap_puz,_i,_j-1)),(c_depth+1,_i,_j-1,4,swap_puz)) if(_j != 2 and prev_move != 4): swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j+1) q.append(c_depth+1+_sum_cost+checkCost(c_cost,simpleHS(c_puz,_i,_j+1),simpleHS(swap_puz,_i,_j),simpleHS(swap_puz,_i,_j+1)),(c_depth+1,_i,_j+1,3,swap_puz)) def checkCost(c_cost,m_cost,c2_cost,m2_cost): return c2_cost - c_cost + m2_cost - m_cost def sumCost(costs): value = 0 for i in range(len(costs)): value += costs[i] return value def simpleHS(c_puz,i,j): if(correctPuz[i*3+j] != c_puz[i*3+j]): return 1 return 0 def HS(i,j,num): k = correctPuz.index(num) ki = (int)(k/3) kj = k - ki*3 value = abs(_i-ki)+abs(_j-kj) return value def swapPuz(c_puz, i, j, i2,j2): c_puz[i2*3+j2],c_puz[i*3+j] = c_puz[i*3+j],c_puz[i2*3+j2] return c_puz def puzzleCheck(c_puz): if(c_puz[8] == 0): for i in range(len(correctPuz)): if(correctPuz[i] != c_puz[i]): return False return True return False correctPuz = [i+1 for i in range(9)] correctPuz[8] = 0 puz = [0 for i in range(9)] i_start = 0 j_start = 0 for i in range(3): puz[i*3],puz[i*3+1],puz[i*3+2] = map(int, input().split()); if(puz[i*3] == 0): i_start,j_start = i,0 elif(puz[i*3+1] == 0): i_start,j_start = i,1 elif(puz[i*3+2] == 0): i_start,j_start = i,2 sumcost=0 for i in range(len(correctPuz)): if(correctPuz[i] != puz[i]): sumcost+=1 finding = 0 depth = 0 while True: if(finding == 1): break iterative(i_start,j_start) depth+=1
s197574275
p02245
u167493070
1525930113
Python
Python3
py
Runtime Error
0
0
2924
import sys; import heapq def iterative(i,j): q = [] q.append(sumcost,0,i,j,0,puz) global finding while len(q): c_dWithH, items = q.pop(0) c_depth = items[0] _i = items[1] _j = items[2] prev_move = items[3] c_puz = items[4] _sum_cost = c_dWithH - c_depth if(c_dWithH - c_depth == 0): finding = 1 print(c_depth) break if(c_dWithH > depth): continue c_cost = simpleHS(c_puz,_i,_j) print(c_depth) if(_i != 0 and prev_move != 1): swap_puz = swapPuz(c_puz[0:],_i,_j,_i-1,_j) q.append(c_depth+1+_sum_cost+checkCost(c_cost,simpleHS(c_puz,_i-1,_j),simpleHS(swap_puz,_i,_j),simpleHS(swap_puz,_i-1,_j)),c_depth+1,_i-1,_j,2,swap_puz) if(_i != 2 and prev_move != 2): swap_puz = swapPuz(c_puz[0:],_i,_j,_i+1,_j) q.append(c_depth+1+_sum_cost+checkCost(c_cost,simpleHS(c_puz,_i+1,_j),simpleHS(swap_puz,_i,_j),simpleHS(swap_puz,_i+1,_j)),c_depth+1,_i+1,_j,1,swap_puz) if(_j != 0 and prev_move != 3): swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j-1) q.append(c_depth+1+_sum_cost+checkCost(c_cost,simpleHS(c_puz,_i,_j-1),simpleHS(swap_puz,_i,_j),simpleHS(swap_puz,_i,_j-1)),c_depth+1,_i,_j-1,4,swap_puz) if(_j != 2 and prev_move != 4): swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j+1) q.append(c_depth+1+_sum_cost+checkCost(c_cost,simpleHS(c_puz,_i,_j+1),simpleHS(swap_puz,_i,_j),simpleHS(swap_puz,_i,_j+1)),c_depth+1,_i,_j+1,3,swap_puz) def checkCost(c_cost,m_cost,c2_cost,m2_cost): return c2_cost - c_cost + m2_cost - m_cost def sumCost(costs): value = 0 for i in range(len(costs)): value += costs[i] return value def simpleHS(c_puz,i,j): if(correctPuz[i*3+j] != c_puz[i*3+j]): return 1 return 0 def HS(i,j,num): k = correctPuz.index(num) ki = (int)(k/3) kj = k - ki*3 value = abs(_i-ki)+abs(_j-kj) return value def swapPuz(c_puz, i, j, i2,j2): c_puz[i2*3+j2],c_puz[i*3+j] = c_puz[i*3+j],c_puz[i2*3+j2] return c_puz def puzzleCheck(c_puz): if(c_puz[8] == 0): for i in range(len(correctPuz)): if(correctPuz[i] != c_puz[i]): return False return True return False correctPuz = [i+1 for i in range(9)] correctPuz[8] = 0 puz = [0 for i in range(9)] i_start = 0 j_start = 0 for i in range(3): puz[i*3],puz[i*3+1],puz[i*3+2] = map(int, input().split()); if(puz[i*3] == 0): i_start,j_start = i,0 elif(puz[i*3+1] == 0): i_start,j_start = i,1 elif(puz[i*3+2] == 0): i_start,j_start = i,2 sumcost=0 for i in range(len(correctPuz)): if(correctPuz[i] != puz[i]): sumcost+=1 finding = 0 depth = 0 while True: if(finding == 1): break iterative(i_start,j_start) depth+=1
s994647825
p02245
u126478680
1527245213
Python
Python3
py
Runtime Error
0
0
1735
class Puzzle: def __init__(self, field=None, path=''): self.f = field self.space = None for i in range(9): if self.f[i] == 9: self.space = i self.path = path def __lt__(self, pzl): # < for i in range(9): if self.f[i] == pzl.f[i]: continue return self.f[i] > pzl.f[i] return False def __gt__(self, pzl): # > for i in range(9): if self.f[i] == pzl.f[i]: continue return self.f[i] < pzl.f[i] return False dx = [-1, 0, 1, 0] dy = [0, -1, 0, 1] dir = ['u', 'l', 'd', 'r'] def is_target(pzl): for i in range(9): if pzl.f[i] != i+1: return False return True def bfs(pzl): queue = deque([]) V = {} pzl.path = '' queue.append(pzl) V[str(pzl.f)] = True if is_target(pzl): return u.path while len(queue) != 0: u = queue.popleft() sx, sy = u.space//3, u.space%3 for r in range(4): tx, ty = sx + dx[r], sy + dy[r] if tx < 0 or ty < 0 or tx >= 3 or ty >= 3: continue v = Puzzle(field=[u.f[i] for i in range(9)], path=u.path) v.f[u.space], v.f[tx*3+ty] = v.f[tx*3+ty], v.f[u.space] v.space = tx*3 + ty if str(v.f) not in V: V[str(v.f)] = True v.path += dir[r] if is_target(v): return v.path queue.append(v) return 'unsolvable' field = [] for i in range(3): field.extend(list(map(int, input().split(' ')))) for i in range(9): if field[i] == 0: field[i] = 9 pzl = Puzzle(field=field) ans= bfs(pzl) print(len(ans))
s801314313
p02245
u126478680
1527245297
Python
Python3
py
Runtime Error
0
0
1736
class Puzzle: def __init__(self, field=None, path=''): self.f = field self.space = None for i in range(9): if self.f[i] == 9: self.space = i self.path = path def __lt__(self, pzl): # < for i in range(9): if self.f[i] == pzl.f[i]: continue return self.f[i] > pzl.f[i] return False def __gt__(self, pzl): # > for i in range(9): if self.f[i] == pzl.f[i]: continue return self.f[i] < pzl.f[i] return False dx = [-1, 0, 1, 0] dy = [0, -1, 0, 1] dir = ['u', 'l', 'd', 'r'] def is_target(pzl): for i in range(9): if pzl.f[i] != i+1: return False return True def bfs(pzl): queue = deque([]) V = {} pzl.path = '' queue.append(pzl) V[str(pzl.f)] = True if is_target(pzl): return u.path while len(queue) != 0: u = queue.popleft() sx, sy = u.space//3, u.space%3 for r in range(4): tx, ty = sx + dx[r], sy + dy[r] if tx < 0 or ty < 0 or tx >= 3 or ty >= 3: continue v = Puzzle(field=[u.f[i] for i in range(9)], path=u.path) v.f[u.space], v.f[tx*3+ty] = v.f[tx*3+ty], v.f[u.space] v.space = tx*3 + ty if str(v.f) not in V: V[str(v.f)] = True v.path += dir[r] if is_target(v): return v.path queue.append(v) return 'unsolvable' field = [] for i in range(3): field.extend(list(map(int, input().split(' ')))) for i in range(9): if field[i] == 0: field[i] = 9 pzl = Puzzle(field=field) ans= bfs(pzl) print(len(ans))
s566803662
p02245
u126478680
1527245328
Python
Python3
py
Runtime Error
2370
31540
1780
from collections import deque, OrderedDict class Puzzle: def __init__(self, field=None, path=''): self.f = field self.space = None for i in range(9): if self.f[i] == 9: self.space = i self.path = path def __lt__(self, pzl): # < for i in range(9): if self.f[i] == pzl.f[i]: continue return self.f[i] > pzl.f[i] return False def __gt__(self, pzl): # > for i in range(9): if self.f[i] == pzl.f[i]: continue return self.f[i] < pzl.f[i] return False dx = [-1, 0, 1, 0] dy = [0, -1, 0, 1] dir = ['u', 'l', 'd', 'r'] def is_target(pzl): for i in range(9): if pzl.f[i] != i+1: return False return True def bfs(pzl): queue = deque([]) V = {} pzl.path = '' queue.append(pzl) V[str(pzl.f)] = True if is_target(pzl): return u.path while len(queue) != 0: u = queue.popleft() sx, sy = u.space//3, u.space%3 for r in range(4): tx, ty = sx + dx[r], sy + dy[r] if tx < 0 or ty < 0 or tx >= 3 or ty >= 3: continue v = Puzzle(field=[u.f[i] for i in range(9)], path=u.path) v.f[u.space], v.f[tx*3+ty] = v.f[tx*3+ty], v.f[u.space] v.space = tx*3 + ty if str(v.f) not in V: V[str(v.f)] = True v.path += dir[r] if is_target(v): return v.path queue.append(v) return 'unsolvable' field = [] for i in range(3): field.extend(list(map(int, input().split(' ')))) for i in range(9): if field[i] == 0: field[i] = 9 pzl = Puzzle(field=field) ans= bfs(pzl) print(len(ans))
s761681232
p02246
u279605379
1534989547
Python
Python3
py
Runtime Error
0
0
1155
from collections import deque def move(P): for i in range(4): for j in range(4): if P[i][j] == 0: r,c = i,j if not r == 0: tmp = [i[:] for i in P] tmp[r][c],tmp[r-1][c] = tmp[r-1][c],tmp[r][c] yield tmp if not r == 3: tmp = [i[:] for i in P] tmp[r][c],tmp[r+1][c] = tmp[r+1][c],tmp[r][c] yield tmp if not c == 0: tmp = [i[:] for i in P] tmp[r][c],tmp[r][c-1] = tmp[r][c-1],tmp[r][c] yield tmp if not c == 3: tmp = [i[:] for i in P] tmp[r][c],tmp[r][c+1] = tmp[r][c+1],tmp[r][c] yield tmp A = [[int(i) for i in input().split()] for _ in range(4)] dp = {dpkey(A) : 1} d = deque([(A,0)]) c = 0 flag = True while(flag): tmp,c = d.pop() for i in move(tmp): key = str(i) if key == "[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]]": ans = c + 1 flag = False elif not key in dp: dp[key] = 1 d.appendleft((i,c+1)) if str(A) == "[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]]": ans = 0 print(ans)
s369327377
p02246
u279605379
1534989570
Python
Python3
py
Runtime Error
0
0
1155
from collections import deque def move(P): for i in range(4): for j in range(4): if P[i][j] == 0: r,c = i,j if not r == 0: tmp = [i[:] for i in P] tmp[r][c],tmp[r-1][c] = tmp[r-1][c],tmp[r][c] yield tmp if not r == 3: tmp = [i[:] for i in P] tmp[r][c],tmp[r+1][c] = tmp[r+1][c],tmp[r][c] yield tmp if not c == 0: tmp = [i[:] for i in P] tmp[r][c],tmp[r][c-1] = tmp[r][c-1],tmp[r][c] yield tmp if not c == 3: tmp = [i[:] for i in P] tmp[r][c],tmp[r][c+1] = tmp[r][c+1],tmp[r][c] yield tmp A = [[int(i) for i in input().split()] for _ in range(4)] dp = {dpkey(A) : 1} d = deque([(A,0)]) c = 0 flag = True while(flag): tmp,c = d.pop() for i in move(tmp): key = str(i) if key == "[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]]": ans = c + 1 flag = False elif not key in dp: dp[key] = 1 d.appendleft((i,c+1)) if str(A) == "[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]]": ans = 0 print(ans)
s669579406
p02246
u279605379
1535079864
Python
Python3
py
Runtime Error
30
6024
1990
from collections import deque import heapq def move(P,p): if p > 3: tmp = P[:] tmp[p],tmp[p-4] = tmp[p-4],tmp[p] tmpp = p - 4 yield tmp,tmpp if p < 12: tmp = P[:] tmp[p],tmp[p+4] = tmp[p+4],tmp[p] tmpp = p + 4 yield tmp,tmpp if p%4 > 0: tmp = P[:] tmp[p],tmp[p-1] = tmp[p-1],tmp[p] tmpp = p - 1 yield tmp,tmpp if p%4 < 3: tmp = P[:] tmp[p],tmp[p+1] = tmp[p+1],tmp[p] tmpp = p + 1 yield tmp,tmpp def evaluate(P): mht = 0 for i,j in enumerate(P): if i+1 == 0: a,b = 3,3 else: a,b = i//4,i%4 if j == 0: c,d = 3,3 else: c,d = (j-1)//4,(j-1)%4 mht += abs(a-c) + abs(b-d) return mht A = [] B = [int(i)%16 for i in range(1,17)] for i in range(4): A+=[int(i) for i in input().split()] dp = {str(A) : (1,0),str(B) : (2,0)} h = [(evaluate(A),A,0,A.index(0))] heapq.heapify(h) e = deque([(B,0,15)]) ans = 46 flag = True while(len(h)>0): mht,tmp,count,p = heapq.heappop(h) for i,j in move(tmp,p): key = str(i) if key in dp: if dp[key][0] == 2: tmpcount = count + 1 + dp[key][1] if tmpcount < ans: ans = tmpcount else: continue else: dp[key] = (1,count+1) mht = evaluate(i) if count+mht//2 < ans: heapq.heappush(h,(mht//2+count,i,count+1,j)) tmp,count,p = e.pop() for i,j in move(tmp,p): key = str(i) if key in dp: if dp[key][0] == 1: ans = dp[key][1] + count + 1 break else: continue else: dp[key] = (2,count+1) e.appendleft((i,count+1,j)) if str(A) == "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]": ans = 0 print(ans)
s727053752
p02246
u279605379
1535131337
Python
Python3
py
Runtime Error
0
0
1289
from collections import deque def move(P): if not r == 0: tmp = [[i for i in j] for j in P] tmp[r][c],tmp[r-1][c] = tmp[r-1][c],tmp[r][c] yield tmp if not r == 3: tmp = [[i for i in j] for j in P] tmp[r][c],tmp[r+1][c] = tmp[r+1][c],tmp[r][c] yield tmp if not c == 0: tmp = [[i for i in j] for j in P] tmp[r][c],tmp[r][c-1] = tmp[r][c-1],tmp[r][c] yield tmp if not c == 3: tmp = [[i for i in j] for j in P] tmp[r][c],tmp[r][c+1] = tmp[r][c+1],tmp[r][c] yield tmp def check(A): for i,j in enumerate(A): for k,l in A: if not i*4+k == l: return False return True A = [[int(i) for i in input().split()] for _ in range(4)] for i in range(4): for j in range(4): if P[i][j] == 0: r,c = i,j dp = {"" : 1} d = deque([(A,0,"",(r,c))]) c = 0 flag = True while(flag): tmp,c = d.pop() for i in move(tmp): key = dpkey(i) if key == "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 ": ans = c + 1 flag = False elif not key in dp: dp[key] = 1 d.appendleft((i,c+1)) if dpkey(A) == "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 ": ans = 0 print(ans)
s988986790
p02246
u279605379
1535132235
Python
Python3
py
Runtime Error
0
0
1673
#双方向 両方 deque from collections import deque def move(P,p): if p > 3: tmp = P[:] tmp[p],tmp[p-4] = tmp[p-4],tmp[p] tmpp = p - 4 yield tmp,tmpp if p < 12: tmp = P[:] tmp[p],tmp[p+4] = tmp[p+4],tmp[p] tmpp = p + 4 yield tmp,tmpp if p%4 > 0: tmp = P[:] tmp[p],tmp[p-1] = tmp[p-1],tmp[p] tmpp = p - 1 yield tmp,tmpp if p%4 < 3: tmp = P[:] tmp[p],tmp[p+1] = tmp[p+1],tmp[p] tmpp = p + 1 yield tmp,tmpp A = [] B = [int(i)%16 for i in range(1,17)] for i in range(4): A+=[int(i) for i in input().split()] dp = {str(A) : 1,str(B) : 2} d = deque([(A,0,A.index(0))]) e = deque([(B,0,15)]) flag = True while(flag): tmp,count,p = d.pop() for i,j in move(tmp,p): key = str(i) if key in dp: if dp[key][0] == 2: ans = count + 1 + dp[key][1] flag = False else: continue elif key == "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]": ans = count + 1 flag = False else: dp[key] = (1,count+1) d.appendleft((i,count+1,j)) tmp,count,p = e.pop() for i,j in move(tmp,p): key = str(i) if key in dp: if dp[key][0] == 1: ans = count + 1 + dp[key][1] flag = False else: continue else: dp[key] == (2,count+1) e.appendleft((i,countL+)) if str(A) == "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]": ans = 0 print(ans)
s330379820
p02246
u279605379
1535316095
Python
Python3
py
Runtime Error
30
6020
1789
from collections import deque import heapq def move(P,p): if p > 3: tmp = P[:] tmp[p],tmp[p-4] = tmp[p-4],tmp[p] tmpp = p - 4 yield tmp,tmpp if p < 12: tmp = P[:] tmp[p],tmp[p+4] = tmp[p+4],tmp[p] tmpp = p + 4 yield tmp,tmpp if p%4 > 0: tmp = P[:] tmp[p],tmp[p-1] = tmp[p-1],tmp[p] tmpp = p - 1 yield tmp,tmpp if p%4 < 3: tmp = P[:] tmp[p],tmp[p+1] = tmp[p+1],tmp[p] tmpp = p + 1 yield tmp,tmpp def evaluate(P,Q): mht = 0 for i in range(16): pi = P.index(i) qi = Q.index(i) pc,pr = pi//4,pi%4 qc,qr = qi//4,qi%4 mht += abs(pc-qc)+abs(pr-qr) return mht A = [] B = [int(i)%16 for i in range(1,17)] for i in range(4): A+=[int(i) for i in input().split()] dp = {str(A) : (1,0),str(B) : (2,0)} h = [(evaluate(A,B),A,0,A.index(0))] heapq.heapify(h) e = deque([(B,0,15)]) ans = 46 flag = True while(flag): mht,tmp,count,p = heapq.heappop(h) for i,j in move(tmp,p): key = str(i) if key in dp: if dp[key][0] == 2: ans = count + 1 + dp[key][1] flag = False else: dp[key] = (1,count+1) mht = evaluate(B,i) if count+mht//2 < ans: heapq.heappush(h,(mht+count,i,count+1,j)) tmp,count,p = e.pop() for i,j in move(tmp,p): key = str(i) if key in dp: if dp[key][0] == 1: ans = count + 1 + dp[key][2] flag = False else: dp[key] = (2,count+1) e.appendleft((i,count+1,j)) if str(A) == "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]": ans = 0 print(ans)
s842807746
p02246
u279605379
1535316415
Python
Python3
py
Runtime Error
0
0
1794
from collections import deque import heapq def move(P,p): if p > 3: tmp = P[:] tmp[p],tmp[p-4] = tmp[p-4],tmp[p] tmpp = p - 4 yield tmp,tmpp if p < 12: tmp = P[:] tmp[p],tmp[p+4] = tmp[p+4],tmp[p] tmpp = p + 4 yield tmp,tmpp if p%4 > 0: tmp = P[:] tmp[p],tmp[p-1] = tmp[p-1],tmp[p] tmpp = p - 1 yield tmp,tmpp if p%4 < 3: tmp = P[:] tmp[p],tmp[p+1] = tmp[p+1],tmp[p] tmpp = p + 1 yield tmp,tmpp def evaluate(P,Q): mht = 0 for i in range(16): pi = P.index(i) qi = Q.index(i) pc,pr = pi//4,pi%4 qc,qr = qi//4,qi%4 mht += abs(pc-qc)+abs(pr-qr) return mht #A = [] B = [int(i)%16 for i in range(1,17)] #for i in range(4): # A+=[int(i) for i in input().split()] dp = {str(A) : (1,0),str(B) : (2,0)} h = [(evaluate(A,B),A,0,A.index(0))] heapq.heapify(h) e = deque([(B,0,15)]) ans = 46 flag = True while(flag): mht,tmp,count,p = heapq.heappop(h) for i,j in move(tmp,p): key = str(i) if key in dp: if dp[key][0] == 2: ans = count + 1 + dp[key][1] flag = False else: dp[key] = (1,count+1) mht = evaluate(B,i) if count+mht//2 < ans: heapq.heappush(h,(mht+count*5,i,count+1,j)) tmp,count,p = e.pop() for i,j in move(tmp,p): key = str(i) if key in dp: if dp[key][0] == 1: ans = count + 1 + dp[key][1] flag = False else: dp[key] = (2,count+1) e.appendleft((i,count+1,j)) if str(A) == "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]": ans = 0 print(ans)
s392459118
p02246
u800534567
1545978306
Python
Python3
py
Runtime Error
0
0
2322
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N 4 #define N2 16 #define LIMIT 80 typedef struct { int b[N2+1]; } Board; Board board; int minstep; typedef enum { R, U, L, D } Direction; typedef struct { int pos; Direction dir; } Motion; // 0 1 2 3 // 4 5 6 7 // 8 9 10 11 // 12 13 14 15 const Motion motion[N2][5] = {{{1,L},{4,U},{-1}}, {{0,R},{2,L},{5,U},{-1}}, {{1,R},{3,L},{6,U},{-1}},{{2,R},{7,U},{-1}}, {{0,D},{5,L},{8,U},{-1}}, {{1,D},{6,L},{9,U},{4,R},{-1}}, {{2,D},{7,L},{10,U},{5,R},{-1}}, {{3,D},{11,U},{6,R},{-1}}, {{4,D},{9,L},{12,U},{-1}}, {{5,D},{10,L},{13,U},{8,R},{-1}}, {{6,D},{11,L},{14,U},{9,R},{-1}}, {{7,D},{15,U},{10,R},{-1}}, {{8,D},{13,L},{-1}}, {{9,D},{14,L},{12,R},{-1}}, {{10,D},{15,L},{13,R},{-1}},{{11,D},{14,R},{-1}}}; const int rr[4][5] = {{0,0,1,0,0},{0,0,0,1,0},{1,0,0,0,0},{0,1,0,0,0}}; int dd[N2][N2]; int dist(int *b) { int i, n, d = 0; for (i=0; i<N2; i++) { n = b[i]-1; if (n<0) { continue; } d += dd[n][i]; } return d; } void search(int step, Motion prev) { int i, d=0; d = dist(board.b); if (step+d>minstep) return; if (d==0) { printf("%d\n", step); exit(0); } Board board_bak = board; for (i=0; motion[prev.pos][i].pos>=0; i++) { Motion m = motion[prev.pos][i]; if (rr[m.dir][prev.dir]) continue; //元に戻るのを防止 board.b[prev.pos] = board.b[m.pos]; board.b[m.pos] = 0; search(step+1, m); board = board_bak; } } int main() { int i, j; for (i=0; i<N2; i++) for (j=0; j<N2; j++) dd[i][j] = abs(i%N-j%N) + abs(i/N-j/N); Board ini_board; fscanf(stdin, "%d %d %d %d\n", &ini_board.b[0],&ini_board.b[1],&ini_board.b[2],&ini_board.b[3]); fscanf(stdin, "%d %d %d %d\n", &ini_board.b[4],&ini_board.b[5],&ini_board.b[6],&ini_board.b[7]); fscanf(stdin, "%d %d %d %d\n", &ini_board.b[8],&ini_board.b[9],&ini_board.b[10],&ini_board.b[11]); fscanf(stdin, "%d %d %d %d\n", &ini_board.b[12],&ini_board.b[13],&ini_board.b[14],&ini_board.b[15]); ini_board.b[N2]=0; Motion m; m.dir = 4; for (i=0; i<N2; i++) if (ini_board.b[i]==0) { m.pos = i; break; } for (minstep=dist(ini_board.b); minstep<=LIMIT; minstep++) { board = ini_board; search(0, m); } puts("no result."); return 0; }
s181272594
p02246
u567380442
1422512049
Python
Python3
py
Runtime Error
0
0
1017
import sys, itertools f = sys.stdin start = [line.split() for line in f] start = tuple(int(x) for y in start for x in y) end =(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0) def next_board(b): brank = b.index(0) if brank % 4: yield b[:brank - 1] + (b[brank], b[brank - 1]) + b[brank + 1:] if brank // 4: yield b[:brank - 4] + (b[brank],)+ b[brank - 3:brank] + (b[brank - 4],) + b[brank + 1:] if brank % 4 != 3: yield b[:brank] + (b[brank + 1], b[brank]) + b[brank + 2:] if brank // 4 != 3: yield b[:brank] + (b[brank + 4],)+ b[brank + 1:brank + 4] + (b[brank],) + b[brank + 5:] d = {start:1, end:-1} #queue = set([(start, 1), (end, -1)]) queue = list([(start, 1), (end, -1)]) while len(queue): u, way = queue.pop(0) for b in next_board(u): if b not in d: d[b] = d[u] + way queue.append((b, way)) elif d[b] * way < 0: print(abs(d[b]) + abs(d[u]) - 1) queue.clear() break
s276618943
p02246
u567380442
1422512513
Python
Python3
py
Runtime Error
0
0
949
start = [input().split() for _ in range(4)] start = tuple(int(x) for y in start for x in y) end =(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0) def next_board(b): brank = b.index(0) if brank % 4: yield b[:brank - 1] + (b[brank], b[brank - 1]) + b[brank + 1:] if brank // 4: yield b[:brank - 4] + (b[brank],)+ b[brank - 3:brank] + (b[brank - 4],) + b[brank + 1:] if brank % 4 != 3: yield b[:brank] + (b[brank + 1], b[brank]) + b[brank + 2:] if brank // 4 != 3: yield b[:brank] + (b[brank + 4],)+ b[brank + 1:brank + 4] + (b[brank],) + b[brank + 5:] d = {start:1, end:-1} queue = list([(start, 1), (end, -1)]) while len(queue): u, way = queue.pop(0) for b in next_board(u): if b not in d: d[b] = d[u] + way queue.append((b, way)) elif d[b] * way < 0: print(abs(d[b]) + abs(d[u]) - 1) queue.clear() break
s349199998
p02246
u567380442
1422514440
Python
Python3
py
Runtime Error
0
0
1117
start = [input().split() for _ in range(4)] start = [x for y in start for x in y] start[start.index('10')] = 'a' start[start.index('11')] = 'b' start[start.index('12')] = 'c' start[start.index('13')] = 'd' start[start.index('14')] = 'e' start[start.index('15')] = 'f' start = ''.join(start) end = '123456789abcdef0' def next_board(b): brank = b.index('0') if brank % 4: yield b[:brank - 1] + b[brank] + b[brank - 1] + b[brank + 1:] if brank // 4: yield b[:brank - 4] + b[brank] + b[brank - 3:brank] + b[brank - 4] + b[brank + 1:] if brank % 4 != 3: yield b[:brank] + b[brank + 1] + b[brank] + b[brank + 2:] if brank // 4 != 3: yield b[:brank] + b[brank + 4]+ b[brank + 1:brank + 4] + b[brank] + b[brank + 5:] d = {start:1, end:-1} queue = collections.deque([(start, 1), (end, -1)]) while len(queue): u, way = queue.popleft() for b in next_board(u): if b not in d: d[b] = d[u] + way queue.append((b, way)) elif d[b] * way < 0: print(abs(d[b]) + abs(d[u]) - 1) queue.clear() break
s567785894
p02246
u567380442
1422515849
Python
Python3
py
Runtime Error
0
0
1014
import sys start = [line.split() for line in sys.stdin] start = [x for y in start for x in y] start[start.index('10')] = 'a' start[start.index('11')] = 'b' start[start.index('12')] = 'c' start[start.index('13')] = 'd' start[start.index('14')] = 'e' start[start.index('15')] = 'f' start = ''.join(start) end = '123456789abcdef0' def next_board(b): z = b.index('0') if z % 4: yield swap(b, z, z - 1) if z // 4: yield swap(b, z, z - 4) if z % 4 != 3: yield swap(b, z, z + 1) if z // 4 != 3: yield swap(b, z, z + 4) def swap(b, i, j): b = list(b) b[i], b[j] = b[j], b[i] return ''.join(b) d = {start:1, end:-1} queue = collections.deque([(start, 1), (end, -1)]) while len(queue): u, way = queue.popleft() for b in next_board(u): if b not in d: d[b] = d[u] + way queue.append((b, way)) elif d[b] * way < 0: print(abs(d[b]) + abs(d[u]) - 1) queue.clear() break
s980415940
p02246
u567380442
1422515901
Python
Python3
py
Runtime Error
0
0
1026
import sys start = [sys.stdin.readline().split() for _ in range(4)] start = [x for y in start for x in y] start[start.index('10')] = 'a' start[start.index('11')] = 'b' start[start.index('12')] = 'c' start[start.index('13')] = 'd' start[start.index('14')] = 'e' start[start.index('15')] = 'f' start = ''.join(start) end = '123456789abcdef0' def next_board(b): z = b.index('0') if z % 4: yield swap(b, z, z - 1) if z // 4: yield swap(b, z, z - 4) if z % 4 != 3: yield swap(b, z, z + 1) if z // 4 != 3: yield swap(b, z, z + 4) def swap(b, i, j): b = list(b) b[i], b[j] = b[j], b[i] return ''.join(b) d = {start:1, end:-1} queue = collections.deque([(start, 1), (end, -1)]) while len(queue): u, way = queue.popleft() for b in next_board(u): if b not in d: d[b] = d[u] + way queue.append((b, way)) elif d[b] * way < 0: print(abs(d[b]) + abs(d[u]) - 1) queue.clear() break
s479692298
p02246
u567380442
1422515967
Python
Python3
py
Runtime Error
0
0
1002
start = [input().split() for _ in range(4)] start = [x for y in start for x in y] start[start.index('10')] = 'a' start[start.index('11')] = 'b' start[start.index('12')] = 'c' start[start.index('13')] = 'd' start[start.index('14')] = 'e' start[start.index('15')] = 'f' start = ''.join(start) end = '123456789abcdef0' def next_board(b): z = b.index('0') if z % 4: yield swap(b, z, z - 1) if z // 4: yield swap(b, z, z - 4) if z % 4 != 3: yield swap(b, z, z + 1) if z // 4 != 3: yield swap(b, z, z + 4) def swap(b, i, j): b = list(b) b[i], b[j] = b[j], b[i] return ''.join(b) d = {start:1, end:-1} queue = collections.deque([(start, 1), (end, -1)]) while len(queue): u, way = queue.popleft() for b in next_board(u): if b not in d: d[b] = d[u] + way queue.append((b, way)) elif d[b] * way < 0: print(abs(d[b]) + abs(d[u]) - 1) queue.clear() break
s769319531
p02246
u603049633
1496637891
Python
Python3
py
Runtime Error
14680
8724
2025
import queue adjacent=( (1,4), (0,2,5), (1,3,6), (2,7), (0,5,8), (1,4,6,9), (2,5,7,10), (3,6,11), (4,9,12), (5,8,10,13), (6,9,11,14), (7,10,15), (8,13), (9,12,14), (10,13,15), (11,14), ) distance = ( (), (0,1,2,3,1,2,3,4,2,3,4,5,3,4,5,6), (1,0,1,2,2,1,2,3,3,2,3,4,4,3,4,5), (2,1,0,1,3,2,1,2,4,3,2,3,5,4,3,4), (3,2,1,0,4,3,2,1,5,4,3,2,6,5,4,3), (1,2,3,4,0,1,2,3,1,2,3,4,2,3,4,5), (2,1,2,3,1,0,1,2,2,1,2,3,3,2,3,4), (3,2,1,2,2,1,0,1,3,2,1,2,4,3,2,3), (4,3,2,1,3,2,1,0,4,3,2,1,5,4,3,2), (2,3,4,5,1,2,3,4,0,1,2,3,1,2,3,4), (3,2,3,4,2,1,2,3,1,0,1,2,2,1,2,3), (4,3,2,3,3,2,1,2,2,1,0,1,3,2,1,2), (5,4,3,2,4,3,2,1,3,2,1,0,4,3,2,1), (3,4,5,6,2,3,4,5,1,2,3,4,0,1,2,3), (4,3,4,5,3,2,3,4,2,1,2,3,1,0,1,2), (5,4,3,4,4,3,2,3,3,2,1,2,2,1,0,1), ) def get_distance(board): v = 0 for x in range(16): p = board[x] if p == 0: continue v += distance[p][x] return v GOAL = [1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,0] board = [] for i in range(4): a,b,c,d = map(int, input().split()) board += [a,b,c,d] move_piece = [None] * 46 def id_lower_search(limit, move, space, lower): global AL if move == limit: if board == GOAL: global count count += 1 i = move_piece[1:].index(None) AL.append(len(move_piece[1:i + 1])) else: for x in adjacent[space]: p = board[x] if move_piece[move] == p: continue board[space] = p board[x] = 0 move_piece[move + 1] = p new_lower = lower - distance[p][x] + distance[p][space] if new_lower + move <= limit: id_lower_search(limit, move + 1, x, new_lower) board[space] = 0 board[x] = p count = 0 n = get_distance(board) AL = [] for x in range(n, 46): id_lower_search(x, 0, board.index(0), n) if count > 0: break print(min(AL))
s814974094
p02246
u426534722
1500493721
Python
Python3
py
Runtime Error
0
0
2236
from sys import stdin import copy dx = tuple(1,0,-1,0) dy = tuple(0,1,0,-1) dir = "ruld" N = 4 N2 = 16 LIMIT = 50 MDT = ((0,1,2,3,1,2,3,4,2,3,4,5,3,4,5,6), (1,0,1,2,2,1,2,3,3,2,3,4,4,3,4,5), (2,1,0,1,3,2,1,2,4,3,2,3,5,4,3,4), (3,2,1,0,4,3,2,1,5,4,3,2,6,5,4,3), (1,2,3,4,0,1,2,3,1,2,3,4,2,3,4,5), (2,1,2,3,1,0,1,2,2,1,2,3,3,2,3,4), (3,2,1,2,2,1,0,1,3,2,1,2,4,3,2,3), (4,3,2,1,3,2,1,0,4,3,2,1,5,4,3,2), (2,3,4,5,1,2,3,4,0,1,2,3,1,2,3,4), (3,2,3,4,2,1,2,3,1,0,1,2,2,1,2,3), (4,3,2,3,3,2,1,2,2,1,0,1,3,2,1,2), (5,4,3,2,4,3,2,1,3,2,1,0,4,3,2,1), (3,4,5,6,2,3,4,5,1,2,3,4,0,1,2,3), (4,3,4,5,3,2,3,4,2,1,2,3,1,0,1,2), (5,4,3,4,4,3,2,3,3,2,1,2,2,1,0,1), (6,5,4,3,5,4,3,2,4,3,2,1,3,2,1,0)) class Puzzle(): def __init__(self): self.f = [0] * N2 self.space, self.MD = 0, 0 state = Puzzle() limit = 0 path = [0] * LIMIT def dfs(depth, prev, limit, state, path): if state.MD == 0: return True if depth + state.MD > limit: return False sx = state.space // N sy = state.space % N tmp = Puzzle() for r in range(4): tx = sx + dx[r] ty = sy + dy[r] if tx < 0 or tx >= N or ty < 0 or ty >= N: continue if max(prev, r) - min(prev, r) == 2: continue tmp = copy.deepcopy(state) state.MD -= MDT[tx * N + ty][state.f[tx * N + ty] - 1] state.MD += MDT[sx * N + sy][state.f[tx * N + ty] - 1] state.f[tx * N + ty], state.f[sx * N + sy] = state.f[sx * N + sy], state.f[tx * N + ty] state.space = tx * N + ty if dfs(depth + 1, r, limit, state, path): path[depth] = r return True state = copy.deepcopy(tmp) return False In = Puzzle() for k in range(N2 // 4): for n, j in enumerate(map(int, stdin.readline().split())): i = k * 4 + n if j == 0: In.f[i] = N2 In.space = i else: In.f[i] = j for i in range(0, N2): if (In.f[i] == N2): continue In.MD += MDT[i][In.f[i] - 1] ans = "" for limit in range(In.MD, LIMIT + 1): state = copy.deepcopy(In) if (dfs(0, -100, limit, state, path)): break print(limit)
s749444236
p02246
u426534722
1500493748
Python
Python3
py
Runtime Error
0
0
2236
from sys import stdin import copy dx = tuple(1,0,-1,0) dy = tuple(0,1,0,-1) dir = "ruld" N = 4 N2 = 16 LIMIT = 50 MDT = ((0,1,2,3,1,2,3,4,2,3,4,5,3,4,5,6), (1,0,1,2,2,1,2,3,3,2,3,4,4,3,4,5), (2,1,0,1,3,2,1,2,4,3,2,3,5,4,3,4), (3,2,1,0,4,3,2,1,5,4,3,2,6,5,4,3), (1,2,3,4,0,1,2,3,1,2,3,4,2,3,4,5), (2,1,2,3,1,0,1,2,2,1,2,3,3,2,3,4), (3,2,1,2,2,1,0,1,3,2,1,2,4,3,2,3), (4,3,2,1,3,2,1,0,4,3,2,1,5,4,3,2), (2,3,4,5,1,2,3,4,0,1,2,3,1,2,3,4), (3,2,3,4,2,1,2,3,1,0,1,2,2,1,2,3), (4,3,2,3,3,2,1,2,2,1,0,1,3,2,1,2), (5,4,3,2,4,3,2,1,3,2,1,0,4,3,2,1), (3,4,5,6,2,3,4,5,1,2,3,4,0,1,2,3), (4,3,4,5,3,2,3,4,2,1,2,3,1,0,1,2), (5,4,3,4,4,3,2,3,3,2,1,2,2,1,0,1), (6,5,4,3,5,4,3,2,4,3,2,1,3,2,1,0)) class Puzzle(): def __init__(self): self.f = [0] * N2 self.space, self.MD = 0, 0 state = Puzzle() limit = 0 path = [0] * LIMIT def dfs(depth, prev, limit, state, path): if state.MD == 0: return True if depth + state.MD > limit: return False sx = state.space // N sy = state.space % N tmp = Puzzle() for r in range(4): tx = sx + dx[r] ty = sy + dy[r] if tx < 0 or tx >= N or ty < 0 or ty >= N: continue if max(prev, r) - min(prev, r) == 2: continue tmp = copy.deepcopy(state) state.MD -= MDT[tx * N + ty][state.f[tx * N + ty] - 1] state.MD += MDT[sx * N + sy][state.f[tx * N + ty] - 1] state.f[tx * N + ty], state.f[sx * N + sy] = state.f[sx * N + sy], state.f[tx * N + ty] state.space = tx * N + ty if dfs(depth + 1, r, limit, state, path): path[depth] = r return True state = copy.deepcopy(tmp) return False In = Puzzle() for k in range(N2 // 4): for n, j in enumerate(map(int, stdin.readline().split())): i = k * 4 + n if j == 0: In.f[i] = N2 In.space = i else: In.f[i] = j for i in range(0, N2): if (In.f[i] == N2): continue In.MD += MDT[i][In.f[i] - 1] ans = "" for limit in range(In.MD, LIMIT + 1): state = copy.deepcopy(In) if (dfs(0, -100, limit, state, path)): break print(limit)
s238468349
p02246
u798803522
1510414925
Python
Python3
py
Runtime Error
0
0
2206
import copy import heapq as hq WIDTH = 4 def hashnum(state): num = "" for i in range(WIDTH): for j in range(WIDTH): num += str(state[i][j]) return num def heauristic(here_x, here_y): return abs((WIDTH - 1) - here_x) + abs((WIDTH - 1) - here_y) ini_state = [] for i in range(WIDTH): temp = [int(n) for n in input().split(" ")] if 0 in temp: zero_x, zero_y = temp.index(0), i ini_state.append(temp) end_state = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]] end_hash = hashnum(end_state) queue = [] hq.heapify(queue) hq.heappush(queue, [0, ini_state, zero_x, zero_y, 0, "start"]) dx = [1, 0, -1, 0] dy = [0, 1, 0, -1] visited = {} visited[hashnum(ini_state)] = [0, "open", "start"] if hashnum(ini_state) == answer: print(0) else: trial = 0 while queue: q = hq.heappop(queue) heauristic_sum_cost, state, zero_x, zero_y, now_cost, direction = q here = hashnum(state) if here == end_hash: print(now_cost) break if here not in visited or visited[here][1] == "open": visited[here][1] = "close" for i in range(len(dx)): new_x = zero_x + dx[i] new_y = zero_y + dy[i] if 0 <= new_x < WIDTH and 0 <= new_y < WIDTH: new_state = copy.deepcopy(state) new_state[new_y][new_x], new_state[zero_y][zero_x] = new_state[zero_y][zero_x], new_state[new_y][new_x] perm = hashnum(new_state) if perm not in visited: estimated_cost = heauristic(zero_x, zero_y) visited[perm] = [now_cost + 1, "open", direction] hq.heappush(queue, [estimated_cost + now_cost + 1, new_state, new_x, new_y, now_cost + 1, "start"]) elif now_cost < visited[perm][0]: visited[perm][0] = now_cost + 1 if visited[perm][1] == "close": visited[perm][1] = "open" hq.heappush(queue, [estimated_cost + now_cost + 1, new_state, new_x, new_y, now_cost + 1, "start"])
s515115311
p02246
u024715419
1513043906
Python
Python3
py
Runtime Error
0
0
2433
import heapq def d_manhattan(node_list): s = 0 for i in range(15): x_goal = i%4 y_goal = i//4 x_now = (node_list[i] - 1)%4 y_now = (node_list[i] - 1)//4 if y_now == -1: y_now = 3 dx = abs(x_now - x_goal) dy = abs(y_now - y_goal) s += dx + dy return s def moveNodeE(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space + 1] = node_tmp[space + 1], node_tmp[space] return node_tmp def moveNodeW(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space - 1] = node_tmp[space - 1], node_tmp[space] return node_tmp def moveNodeN(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space - 3] = node_tmp[space - 3], node_tmp[space] return node_tmp def moveNodeS(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space + 3] = node_tmp[space + 3], node_tmp[space] return node_tmp class board: def __init__(self, node_list, g): self.node = node_list self.space = node_list.index(0) self.g = g self.h = d_manhattan(node_list) self.f = self.g + self.h def makeBoard(self): space = self.space cost_now = self.f x_s = space%4 y_s = space//4 if x_s < 3: node_tmp = moveNodeE(self.node, space) yield board(node_tmp, self.g + 1) if x_s > 0: node_tmp = moveNodeW(self.node, space) yield board(node_tmp, self.g + 1) if y_s < 3: node_tmp = moveNodeS(self.node, space) yield board(node_tmp, self.g + 1) if y_s > 0: node_tmp = moveNodeN(self.node, space) yield board(node_tmp, self.g + 1) b_open = [] n_close = {} n_goal = [1,2,3,4,5,6,7,8,,9,10,11,12,13,14,15,0] n_start = [] for i in range(4): inp = list(map(int, input().split())) n_start.extend(inp) b_start = board(n_start, 0) heapq.heappush(b_open, (b_start.f, b_start.h, 0, b_start)) i = 0 while b_open: _, _, _, b_now = heapq.heappop(b_open) if b_now.node == n_goal: b_goal = b_now break n_close["".join(map(str, b_now.node))] = i for b_new in b_now.makeBoard(): if "".join(map(str, b_new.node)) in n_close: continue heapq.heappush(b_open, (b_new.f, b_new.h, i, b_new)) i += 1 print(b_goal.g)
s655613039
p02246
u024715419
1513044018
Python
Python3
py
Runtime Error
0
0
2433
import heapq def d_manhattan(node_list): s = 0 for i in range(15): x_goal = i%4 y_goal = i//4 x_now = (node_list[i] - 1)%4 y_now = (node_list[i] - 1)//4 if y_now == -1: y_now = 3 dx = abs(x_now - x_goal) dy = abs(y_now - y_goal) s += dx + dy return s def moveNodeE(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space + 1] = node_tmp[space + 1], node_tmp[space] return node_tmp def moveNodeW(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space - 1] = node_tmp[space - 1], node_tmp[space] return node_tmp def moveNodeN(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space - 4] = node_tmp[space - 4], node_tmp[space] return node_tmp def moveNodeS(node_list, space): node_tmp = node_list[:] node_tmp[space], node_tmp[space + 4] = node_tmp[space + 4], node_tmp[space] return node_tmp class board: def __init__(self, node_list, g): self.node = node_list self.space = node_list.index(0) self.g = g self.h = d_manhattan(node_list) self.f = self.g + self.h def makeBoard(self): space = self.space cost_now = self.f x_s = space%4 y_s = space//4 if x_s < 3: node_tmp = moveNodeE(self.node, space) yield board(node_tmp, self.g + 1) if x_s > 0: node_tmp = moveNodeW(self.node, space) yield board(node_tmp, self.g + 1) if y_s < 3: node_tmp = moveNodeS(self.node, space) yield board(node_tmp, self.g + 1) if y_s > 0: node_tmp = moveNodeN(self.node, space) yield board(node_tmp, self.g + 1) b_open = [] n_close = {} n_goal = [1,2,3,4,5,6,7,8,,9,10,11,12,13,14,15,0] n_start = [] for i in range(4): inp = list(map(int, input().split())) n_start.extend(inp) b_start = board(n_start, 0) heapq.heappush(b_open, (b_start.f, b_start.h, 0, b_start)) i = 0 while b_open: _, _, _, b_now = heapq.heappop(b_open) if b_now.node == n_goal: b_goal = b_now break n_close["".join(map(str, b_now.node))] = i for b_new in b_now.makeBoard(): if "".join(map(str, b_new.node)) in n_close: continue heapq.heappush(b_open, (b_new.f, b_new.h, i, b_new)) i += 1 print(b_goal.g)
s134551337
p02246
u859725751
1516588519
Python
Python3
py
Runtime Error
0
0
124
x = input() n = int(input()) for i in range(n): y = input() if y in x: print(1) else: print(0)
s400927142
p02246
u859725751
1516588548
Python
Python3
py
Runtime Error
0
0
124
x = input() n = int(input()) for i in range(n): y = input() if y in x: print(1) else: print(0)
s943403429
p02246
u859725751
1516588556
Python
Python
py
Runtime Error
0
0
124
x = input() n = int(input()) for i in range(n): y = input() if y in x: print(1) else: print(0)
s764038789
p02246
u859725751
1516588586
Python
Python3
py
Runtime Error
0
0
124
x = input() n = int(input()) for i in range(n): y = input() if y in x: print(1) else: print(0)
s914565948
p02246
u859725751
1516588604
Python
Python3
py
Runtime Error
0
0
133
x = input() n = int(input()) print(n) for i in range(n): y = input() if y in x: print(1) else: print(0)
s991464103
p02246
u859725751
1516588624
Python
Python3
py
Runtime Error
0
0
124
x = input() n = int(input()) for i in range(n): y = input() if y in x: print(1) else: print(0)
s663044802
p02246
u426534722
1519922325
Python
Python3
py
Runtime Error
0
0
1009
from heapq import heapify, heappush, heappop N = 4 m = {0: {1, 4}, 1: {0, 2, 5}, 2: {1, 3, 6}, 3: {2, 7}, 4: {0, 5, 8}, 5: {1, 4, 6, 9}, 6: {2, 5, 7, 10}, 7: {3, 6, 11}, 8: {4, 9, 12}, 9: {5, 8, 10, 13}, 10: {6, 9, 11, 14}, 11: {7, 10, 15}, 12: {8, 13}, 13: {9, 12, 14}, 14: {10, 13, 15}, 15: {11, 14}} goal = 0x123456789abcdef0 def g(i, j, a): t = (a >> 4 * j) % 16 return a - (t << 4 * j) + (t << 4 * i) def solve(): MAP = sum((input().split() for _ in range(N)), []) start = int("".join(f"{int(i):x}" for i in MAP), base=16) if start == goal: return 0 zero = 15 - MAP.index("0") dp = [(0, start, zero)] TABLE = {start} while dp: cnt, M, yx = heappop(dp) if M == goal: return cnt cnt += 1 for nyx in m[yx]: key = g(yx, nyx, M) if key in TABLE: continue TABLE.append(key) heappush(dp, (cnt, key, nyx)) def MAIN(): print(solve()) MAIN()
s713710975
p02246
u167493070
1526272342
Python
Python3
py
Runtime Error
30
6064
3915
import sys; import heapq from collections import deque def iterative(i,j): q = deque() q.append((sumcost,0,i,j,0,puz)) global finding while len(q): items = q.pop() cost = items[0] if(cost > depth): continue c_depth = items[1] _i = items[2] _j = items[3] prev_move = items[4] c_puz = items[5] _sum_cost = cost - c_depth if(_sum_cost == 0): finding = 1 print(c_depth) break _i4 = _i*4 c_cost = HS(_i,_j,c_puz[_i4+_j]) #c2_cost = simpleHS(_i,_j,c_puz[_i*4+_j]) if(_i != 0 and prev_move != 1): swap_puz = swapPuz(c_puz[0:],_i,_j,_i-1,_j) n_cost = cost+checkCost(c_cost,HS(_i-1,_j,c_puz[_i4+4+_j]),HS(_i,_j,swap_puz[_i4+_j]),HS(_i-1,_j,swap_puz[_i4-4+_j])) #n_cost += checkCost(c2_cost,simpleHS(_i-1,_j,c_puz[(_i-1)*4+_j]),simpleHS(_i,_j,swap_puz[_i*4+_j]),simpleHS(_i-1,_j,swap_puz[(_i-1)*4+_j])) if(n_cost <= depth): q.append((n_cost,c_depth+1,_i-1,_j,2,swap_puz)) if(_i != 3 and prev_move != 2): swap_puz = swapPuz(c_puz[0:],_i,_j,_i+1,_j) n_cost = cost+checkCost(c_cost,HS(_i+1,_j,c_puz[_i4+4+_j]),HS(_i,_j,swap_puz[_i4+_j]),HS(_i+1,_j,swap_puz[_i4+4+_j])) #n_cost += checkCost(c2_cost,simpleHS(_i+1,_j,c_puz[(_i+1)*4+_j]),simpleHS(_i,_j,swap_puz[_i*4+_j]),simpleHS(_i+1,_j,swap_puz[(_i+1)*4+_j])) if(n_cost <= depth): q.append((n_cost,c_depth+1,_i+1,_j,1,swap_puz)) if(_j != 0 and prev_move != 3): swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j-1) n_cost = cost+checkCost(c_cost,HS(_i,_j-1,c_puz[_i4+_j-1]),HS(_i,_j,swap_puz[_i4+_j]),HS(_i,_j-1,swap_puz[_i4+_j-1])) #n_cost += checkCost(c2_cost,simpleHS(_i,_j-1,c_puz[_i*4+_j-1]),simpleHS(_i,_j,swap_puz[_i*4+_j]),simpleHS(_i,_j-1,swap_puz[_i*4+_j-1])) if(n_cost <= depth): q.append((n_cost,c_depth+1,_i,_j-1,4,swap_puz)) if(_j != 3 and prev_move != 4): swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j+1) n_cost = cost+checkCost(c_cost,HS(_i,_j+1,c_puz[_i4+_j+1]),HS(_i,_j,swap_puz[_i4+_j]),HS(_i,_j+1,swap_puz[_i4+_j+1])) #n_cost += checkCost(c2_cost,simpleHS(_i,_j+1,c_puz[_i*4+_j+1]),simpleHS(_i,_j,swap_puz[_i*4+_j]),simpleHS(_i,_j+1,swap_puz[_i*4+_j+1])) if(n_cost <= depth): q.append((n_cost,c_depth+1,_i,_j+1,3,swap_puz)) def checkCost(c_cost,m_cost,c2_cost,m2_cost): return c2_cost - c_cost + m2_cost - m_cost def sumCost(puz): value = 0 for i in range(4): value += HS(i,0,puz[i*4]) value += HS(i,1,puz[i*4+1]) value += HS(i,2,puz[i*4+2]) value += HS(i,3,puz[i*4+3]) return value def simpleHS(i,j,puz): if(not correctPuz[i+j] == puz): return 1 return 0 def HS(i,j,num): k = num-1 if(k == -1): k = 15 ki = (int)(k/4) kj = k - ki*4 value = abs(i-ki)+abs(j-kj) return value def swapPuz(c_puz, i, j, i2,j2): c_puz[i2*4+j2],c_puz[i*4+j] = c_puz[i*4+j],c_puz[i2*4+j2] return c_puz correctPuz = [i+1 for i in range(16)] correctPuz[15] = 0 puz = [0 for i in range(16)] i_start = 0 j_start = 0 for i in range(4): puz[i*4],puz[i*4+1],puz[i*4+2],puz[i*4+3] = map(int, input().split()); if(puz[i*4] == 0): i_start,j_start = i,0 elif(puz[i*4+1] == 0): i_start,j_start = i,1 elif(puz[i*4+2] == 0): i_start,j_start = i,2 elif(puz[i*4+3] == 0): i_start,j_start = i,3 sumcost = sumCost(puz) #sum2cost = 0 #for i in range(4): # sum2cost += simpleHS(i*4,0,puz[i*4]) # sum2cost += simpleHS(i*4,1,puz[i*4+1]) # sum2cost += simpleHS(i*4,2,puz[i*4+2]) # sum2cost += simpleHS(i*4,3,puz[i*4+3]) finding = 0 depth = 45 iterative(i_start,j_start)
s087145643
p02247
u726330006
1540808782
Python
Python3
py
Runtime Error
20
5576
1080
text=input() string=input() #common_length[i]は、探索列がstring[i]で探索を終了したときに、 # string[i-common_lneght[i] + 1] 〜string[i]で構成される文字列が、探索価値を持つことを示す len_string=len(string) common_length=[0]*len_string tmp=0 tmp_tmp=0 for i in range(1,len_string): if(string[i]==string[tmp]): tmp_tmp=tmp while(string[i]==string[tmp_tmp] and tmp_tmp >0): tmp_tmp=common_length[max([tmp_tmp-1,0])] common_length[i-1]=tmp_tmp tmp+=1 else: common_length[i-1]=tmp while(string[i]!=string[tmp] and tmp>0): tmp=common_length(max([tmp-1,0])) if(string[-1]==string[tmp-1]): common_length[-1]=tmp common_length[0]=0 tmp=0 for i in range(len(text)): if(text[i]!=string[tmp]): while(text[i]!=string[tmp] and tmp>0): tmp=common_length[max([tmp-1,0])] if(text[i]==string[tmp]): tmp+=1 else: tmp+=1 if(tmp==len_string): print(i-tmp+1) tmp=common_length[-1]
s754806796
p02247
u800534567
1546040599
Python
Python3
py
Runtime Error
0
0
500
#include <stdio.h> #include <string.h> int main() { int i, j; char t[1002], p[1002]; fgets(t, 1001, stdin); fgets(p, 1001, stdin); if (t[strlen(t)-1]=='\n') t[strlen(t)-1]='\0'; if (p[strlen(p)-1]=='\n') p[strlen(p)-1]='\0'; int plen = strlen(p); if (plen>strlen(t)) return 0; for (i=0; i<strlen(t)-strlen(p)+1; i++) { if (t[i]==p[0]) { for (j=1; j<plen; j++) { if (t[i+j]!=p[j]) break; } if (j==plen) { printf("%d\n", i); } } } return 0; }
s126036137
p02247
u078042885
1486709654
Python
Python3
py
Runtime Error
0
0
78
t=input();p=input() for i in range(len(t)): if t[i:].startwith(p):print(i)
s174337626
p02247
u603049633
1496647221
Python
Python3
py
Runtime Error
0
0
94
t=input() p=input() lt=len(t) lp=len(p) for i in range(lt-lp+1): if t[i:i+l_p]==p:print(i)
s513399547
p02248
u318430977
1531931130
Python
Python3
py
Runtime Error
20
5564
491
def rabin_karp(T, P, d, q): n = len(T) m = len(P) h = pow(d, m - 1) % q p = 0 t0 = 0 for i in range(m): p = (d * p + P[i]) % q t0 = (d * t0 + T[i]) % q for s in range(n - m + 1): if p == t0: if P[0:(m - 1)] == T[s:(s + m - 1)]: print(s) if s < n - m: t0 = (d * (t0 - T[s] * h) + T[s + m]) % q d = 122 q = 127 t = list(map(ord, input())) p = list(map(ord, input())) rabin_karp(t, p, d, q)
s006823745
p02248
u726330006
1540810396
Python
Python3
py
Runtime Error
0
0
1134
text=input() string=input() #common_length[i]は、探索列がstring[i]で探索を終了したときに、 # string[i-common_lneght[i] + 1] 〜string[i]で構成される文字列が、探索価値を持つことを示す len_string=len(string) common_length=[0]*len_string tmp=0 tmp_tmp=0 for i in range(1,len_string): if(string[i]==string[tmp]): tmp_tmp=tmp while(string[i]==string[tmp_tmp] and tmp_tmp >0): tmp_tmp=common_length[max([tmp_tmp-1,0])] common_length[i-1]=tmp_tmp tmp+=1 else: common_length[i-1]=tmp while(string[i]!=string[tmp] and tmp>0): tmp=common_length[max([tmp-1,0])] if(string[i]==string[0]): tmp=1} if(string[-1]==string[tmp-1]): common_length[-1]=tmp common_length[0]=0 tmp=0 for i in range(len(text)): if(text[i]!=string[tmp]): while(text[i]!=string[tmp] and tmp>0): tmp=common_length[max([tmp-1,0])] if(text[i]==string[tmp]): tmp+=1 else: tmp+=1 if(tmp==len_string): print(i-tmp+1) tmp=common_length[-1]
s696033495
p02248
u798803522
1511458410
Python
Python3
py
Runtime Error
30
7880
3767
## SA-IS from collections import defaultdict def l_or_s_classification(target): length = len(target) l_or_s = ["" for n in range(length)] for i in range(length): if i == length - 1 or target[i] < target[i + 1]: l_or_s[i] = "S" else: l_or_s[i] = "L" return l_or_s def left_most_s(target, l_or_s): length = len(target) lms = [] for i in range(1, length): if l_or_s[i - 1] == "L" and l_or_s[i] == "S": lms.append(i) return lms def get_bucket(target): characters = set(target) bucket_size = [] bucket_capacity = defaultdict(int) bucket_index = {} for t in target: bucket_capacity[t] += 1 for i, c in enumerate(sorted(characters)): bucket_size.append(bucket_capacity[c]) bucket_index[c] = i return (bucket_size, bucket_capacity, bucket_index) def get_bucket_start_end(bucket_size): length = len(bucket_size) temp_start_sum = 0 temp_end_sum = -1 start_index = [0] end_index = [] for i in range(length): temp_start_sum += bucket_size[i] temp_end_sum += bucket_size[i] start_index.append(temp_start_sum) end_index.append(temp_end_sum) start_index.pop() return (start_index, end_index) def lms_bucket_sort(target, bucket_index, end_index, suffix_index, choice): length = len(target) for ch in choice: c = target[ch] this_index = end_index[bucket_index[c]] suffix_index[this_index] = ch end_index[bucket_index[c]] -= 1 def make_suffix_array(target): target += "$" l_or_s = l_or_s_classification(target) lms = left_most_s(target, l_or_s) bucket_size, bucket_capacity, bucket_index = get_bucket(target) start_index, end_index = get_bucket_start_end(bucket_size) lms_end_index = end_index[:] length = len(target) suffix_string = [target[n:] for n in range(length)] suffix_index = [-1 for n in range(length)] lms_bucket_sort(target, bucket_index, lms_end_index, suffix_index, lms) # print(suffix_string) # print(suffix_index, lms, l_or_s) for suf in suffix_index: if suf != -1 and l_or_s[suf - 1] == "L": c = target[suf - 1] suffix_index[start_index[bucket_index[c]]] = suf - 1 start_index[bucket_index[c]] += 1 # print(suffix_index) for i in range(length - 1, -1, -1): suf = suffix_index[i] if suf != -1 and l_or_s[suf - 1] == "S": c = target[suf - 1] suffix_index[end_index[bucket_index[c]]] = suf - 1 end_index[bucket_index[c]] -= 1 suffix_array = [suffix_string[n] for n in suffix_index] # print(suffix_index) return (suffix_array, suffix_index) def binary_range_search(suffix_array, pattern): length = len(suffix_array) left = 0 temp_r = length - 1 pat_len = len(pattern) while left < temp_r: mid = (left + temp_r) // 2 comp_len = min(len(suffix_array[mid]), pat_len) if pattern[:comp_len] <= suffix_array[mid][:comp_len]: temp_r = mid else: left = mid + 1 right = length - 1 temp_l = 0 while temp_l < right: mid = (temp_l + right - 1) // 2 comp_len = min(len(suffix_array[mid]), pat_len) if pattern[:comp_len] >= suffix_array[mid][:comp_len]: temp_l = mid + 1 else: right = mid - 1 if left == right and suffix_array[:pat_len] != pattern: return [] else: return [left, right] suffix_array, suffix_index = make_suffix_array(input().strip()) match_range = binary_range_search(suffix_array, input().strip()) for i in sorted(suffix_index[match_range[0]:match_range[1] + 1]): print(i)
s686962000
p02248
u798803522
1511458492
Python
Python3
py
Runtime Error
30
7904
3849
## SA-IS from collections import defaultdict def l_or_s_classification(target): length = len(target) l_or_s = ["" for n in range(length)] for i in range(length): if i == length - 1 or target[i] < target[i + 1]: l_or_s[i] = "S" else: l_or_s[i] = "L" return l_or_s def left_most_s(target, l_or_s): length = len(target) lms = [] for i in range(1, length): if l_or_s[i - 1] == "L" and l_or_s[i] == "S": lms.append(i) return lms def get_bucket(target): characters = set(target) bucket_size = [] bucket_capacity = defaultdict(int) bucket_index = {} for t in target: bucket_capacity[t] += 1 for i, c in enumerate(sorted(characters)): bucket_size.append(bucket_capacity[c]) bucket_index[c] = i return (bucket_size, bucket_capacity, bucket_index) def get_bucket_start_end(bucket_size): length = len(bucket_size) temp_start_sum = 0 temp_end_sum = -1 start_index = [0] end_index = [] for i in range(length): temp_start_sum += bucket_size[i] temp_end_sum += bucket_size[i] start_index.append(temp_start_sum) end_index.append(temp_end_sum) start_index.pop() return (start_index, end_index) def lms_bucket_sort(target, bucket_index, end_index, suffix_index, choice): length = len(target) for ch in choice: c = target[ch] this_index = end_index[bucket_index[c]] suffix_index[this_index] = ch end_index[bucket_index[c]] -= 1 def make_suffix_array(target): target += "$" l_or_s = l_or_s_classification(target) lms = left_most_s(target, l_or_s) bucket_size, bucket_capacity, bucket_index = get_bucket(target) start_index, end_index = get_bucket_start_end(bucket_size) lms_end_index = end_index[:] length = len(target) suffix_string = [target[n:] for n in range(length)] suffix_index = [-1 for n in range(length)] lms_bucket_sort(target, bucket_index, lms_end_index, suffix_index, lms) # print(suffix_string) # print(suffix_index, lms, l_or_s) for suf in suffix_index: if suf != -1 and l_or_s[suf - 1] == "L": c = target[suf - 1] suffix_index[start_index[bucket_index[c]]] = suf - 1 start_index[bucket_index[c]] += 1 # print(suffix_index) for i in range(length - 1, -1, -1): suf = suffix_index[i] if suf != -1 and l_or_s[suf - 1] == "S": c = target[suf - 1] suffix_index[end_index[bucket_index[c]]] = suf - 1 end_index[bucket_index[c]] -= 1 suffix_array = [suffix_string[n] for n in suffix_index] # print(suffix_index) return (suffix_array, suffix_index) def binary_range_search(suffix_array, pattern): length = len(suffix_array) left = 0 temp_r = length - 1 pat_len = len(pattern) while left < temp_r: mid = (left + temp_r) // 2 comp_len = min(len(suffix_array[mid]), pat_len) if pattern[:comp_len] <= suffix_array[mid][:comp_len]: temp_r = mid else: left = mid + 1 right = length - 1 temp_l = 0 while temp_l < right: mid = (temp_l + right - 1) // 2 comp_len = min(len(suffix_array[mid]), pat_len) if pattern[:comp_len] >= suffix_array[mid][:comp_len]: temp_l = mid + 1 else: right = mid - 1 if left == right and suffix_array[:pat_len] != pattern: return [] else: return [left, right] target = input().strip() pattern = input().strip() if len(target) >= len(pattern): suffix_array, suffix_index = make_suffix_array(target) match_range = binary_range_search(suffix_array, pattern) for i in sorted(suffix_index[match_range[0]:match_range[1] + 1]): print(i)
s368067303
p02248
u798803522
1511459371
Python
Python3
py
Runtime Error
50
7876
3849
## SA-IS from collections import defaultdict def l_or_s_classification(target): length = len(target) l_or_s = ["" for n in range(length)] for i in range(length): if i == length - 1 or target[i] < target[i + 1]: l_or_s[i] = "S" else: l_or_s[i] = "L" return l_or_s def left_most_s(target, l_or_s): length = len(target) lms = [] for i in range(1, length): if l_or_s[i - 1] == "L" and l_or_s[i] == "S": lms.append(i) return lms def get_bucket(target): characters = set(target) bucket_size = [] bucket_capacity = defaultdict(int) bucket_index = {} for t in target: bucket_capacity[t] += 1 for i, c in enumerate(sorted(characters)): bucket_size.append(bucket_capacity[c]) bucket_index[c] = i return (bucket_size, bucket_capacity, bucket_index) def get_bucket_start_end(bucket_size): length = len(bucket_size) temp_start_sum = 0 temp_end_sum = -1 start_index = [0] end_index = [] for i in range(length): temp_start_sum += bucket_size[i] temp_end_sum += bucket_size[i] start_index.append(temp_start_sum) end_index.append(temp_end_sum) start_index.pop() return (start_index, end_index) def lms_bucket_sort(target, bucket_index, end_index, suffix_index, choice): length = len(target) for ch in choice: c = target[ch] this_index = end_index[bucket_index[c]] suffix_index[this_index] = ch end_index[bucket_index[c]] -= 1 def make_suffix_array(target): target += "$" l_or_s = l_or_s_classification(target) lms = left_most_s(target, l_or_s) bucket_size, bucket_capacity, bucket_index = get_bucket(target) start_index, end_index = get_bucket_start_end(bucket_size) lms_end_index = end_index[:] length = len(target) suffix_string = [target[n:] for n in range(length)] suffix_index = [-1 for n in range(length)] lms_bucket_sort(target, bucket_index, lms_end_index, suffix_index, lms) # print(suffix_string) # print(suffix_index, lms, l_or_s) for suf in suffix_index: if suf != -1 and l_or_s[suf - 1] == "L": c = target[suf - 1] suffix_index[start_index[bucket_index[c]]] = suf - 1 start_index[bucket_index[c]] += 1 # print(suffix_index) for i in range(length - 1, -1, -1): suf = suffix_index[i] if suf != -1 and l_or_s[suf - 1] == "S": c = target[suf - 1] suffix_index[end_index[bucket_index[c]]] = suf - 1 end_index[bucket_index[c]] -= 1 suffix_array = [suffix_string[n] for n in suffix_index] # print(suffix_index) return (suffix_array, suffix_index) def binary_range_search(suffix_array, pattern): length = len(suffix_array) left = 0 temp_r = length - 1 pat_len = len(pattern) while left < temp_r: mid = (left + temp_r) // 2 comp_len = min(len(suffix_array[mid]), pat_len) if pattern[:comp_len] > suffix_array[mid][:comp_len]: left = mid + 1 else: temp_r = mid right = length - 1 temp_l = 0 while temp_l < right: mid = (temp_l + right + 1) // 2 comp_len = min(len(suffix_array[mid]), pat_len) if pattern[:comp_len] < suffix_array[mid][:comp_len]: right = mid - 1 else: temp_l = mid if left == right and suffix_array[left][:pat_len] != pattern: return [] else: return [left, right] target = input().strip() pattern = input().strip() if len(target) >= len(pattern): suffix_array, suffix_index = make_suffix_array(target) match_range = binary_range_search(suffix_array, pattern) for i in sorted(suffix_index[match_range[0]:match_range[1] + 1]): print(i)
s485985739
p02248
u426534722
1520179144
Python
Python3
py
Runtime Error
0
0
824
def kmpTable(w): lw = len(w) nx = [-1] * (lw + 1) j = -1 for i in xrange(lw): while j >= 0 and w[i] != w[j]: j = nx[j] j += 1 nx[i + 1] = j return nx def kmpSearch(s, w): ls = len(s) start = 0 w_idx = 0 ret = [] nx = kmpTable(w) while start + w_idx < ls: if s[start + w_idx] == w[w_idx]: w_idx += 1 if w_idx == len(w): ret.append(start) start = start + w_idx - nx[w_idx] w_idx = nx[w_idx] else: if w_idx == 0: start += 1 else: start = start + w_idx - nx[w_idx] w_idx = nx[w_idx] return ret T = raw_input() P = raw_input() ans = kmpSearch(T, P) for i in ans: print(i)
s664245220
p02248
u426534722
1520179170
Python
Python3
py
Runtime Error
0
0
816
def kmpTable(w): lw = len(w) nx = [-1] * (lw + 1) j = -1 for i in xrange(lw): while j >= 0 and w[i] != w[j]: j = nx[j] j += 1 nx[i + 1] = j return nx def kmpSearch(s, w): ls = len(s) start = 0 w_idx = 0 ret = [] nx = kmpTable(w) while start + w_idx < ls: if s[start + w_idx] == w[w_idx]: w_idx += 1 if w_idx == len(w): ret.append(start) start = start + w_idx - nx[w_idx] w_idx = nx[w_idx] else: if w_idx == 0: start += 1 else: start = start + w_idx - nx[w_idx] w_idx = nx[w_idx] return ret T = input() P = input() ans = kmpSearch(T, P) for i in ans: print(i)
s366943866
p02248
u150984829
1524900520
Python
Python3
py
Runtime Error
0
0
102
def f(T,P):for i in range(len(T)):P!=T[i:i+len(P)]or print(i) if'__main__'__name__:f(input(),input())
s707681381
p02248
u150984829
1524900543
Python
Python3
py
Runtime Error
0
0
104
def f(T,P): for i in range(len(T)):P!=T[i:i+len(P)]or print(i) if'__main__'__name__:f(input(),input())
s635553627
p02248
u138546245
1527127748
Python
Python3
py
Runtime Error
0
0
304
def search_by_dict(s1, s2): d = defaultdict(list) for i in range(len(s1)-len(s2)): d[s1[i:i+len(s2)]].append(i) return (i for i in d[s2]) def run(): s1 = input() s2 = input() for idx in search_by_dict(s1, s2): print(idx) if __name__ == '__main__': run()
s895112503
p02248
u138546245
1527147783
Python
Python3
py
Runtime Error
20
5572
1259
class RKSearch: shift = 40 size = 33554393 def __init__(self, s1, s2): self.haystack = self.encode(s1) self.needle = self.encode(s2) def find(self): m, n = len(self.haystack), len(self.needle) h1 = self.hash(self.haystack, n) h2 = self.hash(self.needle, n) dm = self.shift**(n-1) % self.size for i in range(m-n+1): if h1 == h2: yield i if i+n < m: h1 = ((h1 - self.haystack[i]*dm) * self.shift + self.haystack[i+n]) % self.size def hash(self, s, length): h = 0 for i in range(length): h = (h * self.shift + s[i]) % self.size return h def encode(cls, s): basea = int.from_bytes(b'a', 'little') based = int.from_bytes(b'0', 'little') bs = [] for c in s: if c.isdigit(): bs.append(int.from_bytes(c.encode('utf8'), 'little')-based+27) else: bs.append(int.from_bytes(c.encode('utf8'), 'little')-basea) return bs def run(): s1 = input() s2 = input() rk = RKSearch(s1, s2) for i in rk.find(): print(i) if __name__ == '__main__': run()
s353556458
p02249
u726330006
1540913909
Python
Python3
py
Runtime Error
20
5640
3106
def get_common(string,len_string): common_length=[0]*len_string tmp=0 tmp_tmp=0 for i in range(1,len_string): if(string[i]==string[tmp]): tmp_tmp=tmp while(string[i]==string[tmp_tmp] and tmp_tmp >0): tmp_tmp=common_length[max([tmp_tmp-1,0])] common_length[i-1]=tmp_tmp tmp+=1 else: common_length[i-1]=tmp while(string[i]!=string[tmp] and tmp>0): tmp=common_length[max([tmp-1,0])] if(string[i]==string[tmp]): tmp+=1 if(string[-1]==string[tmp-1]): common_length[-1]=tmp common_length[0]=0 return common_length def find_str(field,field_row,pattern,common_length,H,W,h,w): tmp=0 column_list=[] len_pattern=len(pattern[0]) for i in range(len(field[field_row])): if(field[field_row][i]!=pattern[0][tmp]): while(field[field_row][i]!=pattern[0][tmp] and tmp>0): tmp=common_length[0][max([tmp-1,0])] if(field[field_row][i]==pattern[0][tmp]): tmp+=1 else: tmp+=1 if(tmp==len_pattern): column_list.append(i-tmp+1) tmp=common_length[0][-1] for j in range(1,h): tmp=0 for loop in range(len(column_list)): column=column_list[loop] if(loop < len(column_list) -1): next_column=column_list[loop+1] else: next_column=len(field[0])+len(pattern[0])+1 ini_tmp=tmp for i in range(0,len_pattern+1): if(field[field_row+j][column+ i+ini_tmp]!=pattern[j][tmp]): if(i < next_column - column): tmp=0 column_list.pop(loop) break else: while(tmp>column+i-next_column+1): tmp=common_length[0][max([tmp-1,0])] if(tmp!=column+i-next_column+1): tmp=0 column_list.pop(loop) break else: tmp+=1 if(tmp==len_pattern): if(i < next_column - column): tmp=0 break else: while(tmp>column+i-next_column+1): tmp=common_length[0][max([tmp-1,0])] if(tmp!=column+i-next_column+1): tmp=0 break for column in column_list: print(f"{field_row} {column}") H,W=map(int,input().split()) field=[] for i in range(H): field.append(input()) h,w=map(int,input().split()) pattern=[] for i in range(h): pattern.append(input()) common_length=[] for i in range(h): common_length.append(get_common(pattern[i],w)) for i in range(H-h+1): find_str(field,i,pattern,common_length,H,W,h,w)
s623033506
p02249
u831244171
1487579317
Python
Python3
py
Runtime Error
30
7660
696
H, W = map(int,input().split()) A = [] for i in range(H): A.append(input()) R, C = map(int,input().split()) B = [] for i in range(R): B.append(input()) b = B[0] b_for_move = [0 for i in range(len(B))] for i in range(len(b)): for j in range(0,len(b)-i)[::-1]: if b[i:i+j] == b[len(b)-j-1:len(b)]: b_for_move[i] = j break else: b_for_move[i] = 1 for i in range(H-R + 1): for k in range(W-C +1): count = 0 for j in range(R): if B[j] == A[i+j][k:k+C]: count += 1 else: i += b_for_move[j] -1 break if count == R: print(i,k)
s149377228
p02249
u831244171
1487579651
Python
Python3
py
Runtime Error
20
7728
712
H, W = map(int,input().split()) A = [] for i in range(H): A.append(input()) R, C = map(int,input().split()) B = [] for i in range(R): B.append(input()) b = B[0] b_for_move = [0 for i in range(len(b))] for i in range(len(b)): for j in range(0,len(b)-i)[::-1]: if b[i:i+j] == b[len(b)-j-1:len(b)]: b_for_move[i] = j break else: b_for_move[i] = 1 for i in range(H-R + 1): for k in range(W-C +1): count = 0 for j in range(R): if B[j] == A[i+j][k:k+C]: count += 1 else: i += b_for_move[j] -1 break if count == R: print(i,k)
s259544594
p02249
u831244171
1487675708
Python
Python3
py
Runtime Error
0
0
1383
CSIZE = 256 def make_bm_table(pattern,size): bm_table = [size]*CSIZE for i in range(size): dist = size-i-1 charac = pattern[i] bm_table[ord(charac)] = dist return bm_table def bm_search(pattern,buff): size = R bm_table = make_bm_table(pattern[0], size) buffsize = W for j in range(H-C): saikobi = size-1 while saikobi < buffsize: for i in range(size): if pattern[0][size-i-1] != buff[j][saikobi-i]: saikobi += max(bm_table[ord(buff[j][saikobi-i])]-i,1) break else: count = 1 for k in range(1,R): for l in range(C)[::-1]: if pattern[k][size-1-l] != buff[j+k][saikobi-l]: count = 0 break if count == 0: break else: print(j,saikobi-C+2) saikobi += 1 H,W = map(int,input().split()) buff = [""]*H for i in range(H): buff[i] = input() R,C = map(int,input().split()) pattern = [""]*R for i in range(R): pattern[i] = input() bm_search(pattern, buff)
s971180593
p02249
u426534722
1520350527
Python
Python3
py
Runtime Error
0
0
1310
base1 = 1009 base2 = 1013 mask = (1 << 32) - 1 def calc_hash(f, r, c): global ph, pw, h tmp = [[0] * c for _ in range(r)] dr, dc = r - ph, c - pw t1 = 1 for _ in range(pw): t1 = (t1 * base1) & mask for i in range(r): e = 0 for j in range(pw): e = e * base1 + f[i][j] for j in range(dc): tmp[i][j] = e e = (e * base1 - t1 * f[i][j] + f[i][j + pw]) & mask tmp[i][dc] = e t2 = 1 for _ in range(ph): t2 = (t2 * base2) & mask for j in range(dc + 1): e = 0 for i in range(ph): e = e * base2 + tmp[i][j] for i in range(dr): h[i][j] = e e = (e * base2 - t2 * tmp[i][j] + tmp[i + ph][j]) & mask h[dr][j] = e th, tw = map(int, input().split()) t = tuple(tuple(ord(c) for c in input()) for _ in range(th)) ph, pw = map(int, input().split()) p = tuple(tuple(ord(c) for c in input()) for _ in range(ph)) ans = [] if th >= ph and tw >= pw: h = [[0] * tw for _ in range(th)] calc_hash(p, ph, pw) key = h[0][0] & mask calc_hash(t, th, tw) for i in range(th - ph + 1): for j in range(tw - pw + 1): if h[i][j] & mask == key: ans.append(f"{i} {j}") if ans: print("\n".join(a for a in ans))
s181725274
p02249
u426534722
1520350941
Python
Python3
py
Runtime Error
0
0
1357
base1 = 1009 base2 = 1013 mask = (1 << 32) - 1 def calc_hash(f, r, c): global ph, pw, h tmp = [[0] * c for _ in range(r)] dr, dc = r - ph, c - pw t1 = 1 t1 = (t1 * (base1 ** pw)) & mask # for _ in range(pw): # t1 = (t1 * base1) & mask for i in range(r): e = 0 for j in range(pw): e = e * base1 + f[i][j] for j in range(dc): tmp[i][j] = e e = (e * base1 - t1 * f[i][j] + f[i][j + pw]) & mask tmp[i][dc] = e t2 = 1 for _ in range(ph): t2 = (t2 * base2) & mask for j in range(dc + 1): e = 0 for i in range(ph): e = e * base2 + tmp[i][j] for i in range(dr): h[i][j] = e e = (e * base2 - t2 * tmp[i][j] + tmp[i + ph][j]) & mask h[dr][j] = e th, tw = map(int, input().split()) t = tuple(tuple(ord(c) for c in input()) for _ in range(th)) ph, pw = map(int, input().split()) p = tuple(tuple(ord(c) for c in input()) for _ in range(ph)) ans = [] if th >= ph and tw >= pw: h = [[0] * tw for _ in range(th)] calc_hash(p, ph, pw) key = h[0][0] & mask calc_hash(t, th, tw) for i in range(th - ph + 1): for j in range(tw - pw + 1): if h[i][j] & mask == key: ans.append(f"{i} {j}") if ans: print("\n".join(a for a in ans))
s485503586
p02250
u797673668
1455113734
Python
Python3
py
Runtime Error
0
0
691
base = 127 mask = (1 << 32) - 1 def calc_hash(f, pl, tl): dl = tl - pl tmp = set() t = 1 for _ in range(pl): t = (t * base) & mask e = 0 for i in range(pl): e = e * base + f[i] for i in range(dl): tmp.add(e) e = (e * base - t * f[i] + f[i + pl]) & mask tmp.add(e) return tmp t = [ord(c) for c in input().strip()] tl = len(t) q = int(input()) h = dict() while q: p = [ord(c) for c in input().strip()] pl = len(p) key = calc_hash(p, pl, pl).pop() & mask if pl in h: haystack = h[pl] else: haystack = calc_hash(t, pl, tl) h[pl] = haystack print(1 if key in haystack else 0)
s849256173
p02250
u797673668
1455113767
Python
Python3
py
Runtime Error
20
7732
702
base = 127 mask = (1 << 32) - 1 def calc_hash(f, pl, tl): dl = tl - pl tmp = set() t = 1 for _ in range(pl): t = (t * base) & mask e = 0 for i in range(pl): e = e * base + f[i] for i in range(dl): tmp.add(e) e = (e * base - t * f[i] + f[i + pl]) & mask tmp.add(e) return tmp t = [ord(c) for c in input().strip()] tl = len(t) q = int(input()) h = dict() while q: p = [ord(c) for c in input().strip()] pl = len(p) key = calc_hash(p, pl, pl).pop() & mask if pl in h: haystack = h[pl] else: haystack = calc_hash(t, pl, tl) h[pl] = haystack print(1 if key in haystack else 0) q -= 1
s326879085
p02250
u797673668
1455251705
Python
Python3
py
Runtime Error
0
0
1451
base = 127 mask = (1 << 32) - 1 def calc_hash(f, pl, tl, with_array): dl = tl - pl tmp = [] t = 1 for _ in range(pl): t = (t * base) & mask e = 0 for i in range(pl): e = (e * base + f[i]) & mask for i in range(dl): tmp.append(e) e = (e * base - t * f[i] + f[i + pl]) & mask tmp.append(e) if with_array: return set(tmp), tmp else: return set(tmp) t = [ord(c) for c in input().strip()] tl = len(t) q = int(input()) h = dict() while q: p = [ord(c) for c in input().strip()] pl = len(p) if pl > tl: print(0) q -= 1 continue if pl >= 10: keys_set, keys_array = calc_hash(p, 10, pl, with_array=True) keys0, keys1 = keys_array[0], keys_array[1:pl - 9] if pl not in h: hash_set, hash_array = h[10] = calc_hash(t, 10, tl, with_array=True) else: hash_set, hash_array = h[10] if keys_set.issubset(hash_set): for idx, hash in enumerate(hash_array): if keys0 == hash and hash_array[idx + 1:idx + pl - 9] == keys1: print(1) break else: print(0) else: print(0) else: key = calc_hash(p, pl, pl).pop() & mask if pl not in h: h[pl] = calc_hash(t, pl, tl, with_array=False) print(1 if key in h[pl] else 0) q -= 1
s862746859
p02250
u159356473
1481789281
Python
Python3
py
Runtime Error
20
7644
555
#coding:utf-8 def MSM(T,P): Tlist=list(T) Plist=list(P) ans=0 for i in range(len(Tlist)): if Tlist[i]==Plist[0]: ans+=1 for j in range(1,len(Plist)): if Plist[j]==Tlist[i+j] and i+j<=len(Tlist): ans+=1 if ans==len(Plist): return 1 return 0 if __name__=="__main__": T=input() n=int(input()) ans=[] for i in range(n): P=input() ans.append(MSM(T,P)) for i in range(n): print(ans[i])