input stringlengths 20 127k | target stringlengths 20 119k | problem_id stringlengths 6 6 |
|---|---|---|
#
# Written by NoKnowledgeGG @YlePhan
# ('ω')
#
#import math
#mod = 10**9+7
#import itertools
#import fractions
#import numpy as np
#mod = 10**4 + 7
"""def kiri(n,m):
r_ = n / m
if (r_ - (n // m)) > 0:
return (n//m) + 1
else:
return (n//m)"""
""" n! mod m 階乗
mod = 1e9 + 7
N = 10000000
fac = [0] * N
def ini():
fac[0] = 1 % mod
for i in range(1,N):
fac[i] = fac[i-1] * i % mod"""
"""mod = 1e9+7
N = 10000000
pw = [0] * N
def ini(c):
pw[0] = 1 % mod
for i in range(1,N):
pw[i] = pw[i-1] * c % mod"""
"""
def YEILD():
yield 'one'
yield 'two'
yield 'three'
generator = YEILD()
print(next(generator))
print(next(generator))
print(next(generator))
"""
"""def gcd_(a,b):
if b == 0:#結局はc,0の最大公約数はcなのに
return a
return gcd_(a,a % b) # a = p * b + q"""
"""def extgcd(a,b,x,y):
d = a
if b!=0:
d = extgcd(b,a%b,y,x)
y -= (a//b) * x
print(x,y)
else:
x = 1
y = 0
return d"""
def readInts():
return list(map(int,input().split()))
mod = 10**9 + 7
#def main():
n,m = readInts()
a = [0] * m
b = [0] * m
graph = [[False for i in range(n)] for j in range(n)]
for i in range(m):
a[i],b[i] = list(map(int,input().split()))
a[i] -=1
b[i] -=1
graph[a[i]][b[i]] = True
graph[b[i]][a[i]] = True
cnt = 0
now = [0] * n
def dfs(pos,nya):
global cnt
if pos == n:
if now[0] == 0:
for i in range(n-1):
if graph[now[i]][now[i+1]] == False:
break
if i == n-2:
cnt += 1
return
for i in range(n):
if nya & (1 << i):
now[pos] = i
dfs(pos+1,nya^(1<<i))
dfs(0,(1<<n)-1)
print(cnt)
#if __name__ == '__main__':
# main() | n, m = list(map(int,input().split()))
G = [[] for _ in range(n)]
for i in range(m):
a,b = [int(x)-1 for x in input().split()]
G[a].append(b)
G[b].append(a)
SAW = [False] * n
def dfs(v,SAW):
global res
end = True
for i in range(n):
if not SAW[i] and i != v:
end = False
if end:
res += 1
return
SAW[v] = True
for nv in G[v]:
if SAW[nv]:
continue
dfs(nv,SAW)
SAW[v] = False
res = 0
dfs(0,SAW)
print(res)
| p03805 |
import sys
import copy
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
in_n = lambda: int(readline())
in_nn = lambda: list(map(int, readline().split()))
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: list(map(int, read().split()))
in_s = lambda: readline().rstrip().decode('utf-8')
sys.setrecursionlimit(1000000)
ans = 0
def bfs(N, edge, v, search):
search |= {v}
global ans
if len(search) == N:
ans += 1
return
for e in edge[v]:
if e not in search:
#print('test:{},{},{}'.format(e, v, search))
bfs(N, edge, e, copy.copy(search))
def main():
N, M = in_nn()
edge = [[] for _ in range(N)]
for i in range(M):
a, b = in_nn()
a, b = a - 1, b - 1
edge[a].append(b)
edge[b].append(a)
bfs(N, edge, 0, set())
print(ans)
if __name__ == '__main__':
main()
| import sys
import copy
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
in_n = lambda: int(readline())
in_nn = lambda: list(map(int, readline().split()))
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: list(map(int, read().split()))
in_s = lambda: readline().rstrip().decode('utf-8')
sys.setrecursionlimit(1000000)
ans = 0
def bfs(N, edge, v, search):
search |= {v}
global ans
if len(search) == N:
ans += 1
return
for e in edge[v]:
if e not in search:
bfs(N, edge, e, copy.copy(search))
def main():
N, M = in_nn()
edge = [[] for _ in range(N)]
for i in range(M):
a, b = in_nn()
a, b = a - 1, b - 1
edge[a].append(b)
edge[b].append(a)
bfs(N, edge, 0, set())
print(ans)
if __name__ == '__main__':
main()
| p03805 |
import sys
sys.setrecursionlimit(10000000)
import copy
n, m = list(map(int, input().split()))
graph = [list() for i in range(n+1)]
for i in range(m):
a, b = list(map(int, (input().split())))
graph[a] += [b]
graph[b] += [a]
ans = 0
def dfs(visited, now):
tv = copy.copy(visited)
tv[now-1] = True
if all(tv):
return 1
temp = 0
for i in graph[now]:
if tv[i-1] != 1:
temp += dfs(tv, i)
return temp
ans = dfs([False] * n, 1)
print(ans) | import copy
n, m = list(map(int, input().split()))
graph = [list() for i in range(n+1)]
for i in range(m):
a, b = list(map(int, (input().split())))
graph[a] += [b]
graph[b] += [a]
def dfs(visited, now):
tv = copy.copy(visited)
tv[now-1] = 1
if all(tv) == 1:
return 1
count = 0
for i in graph[now]:
if tv[i-1] == 0:
count += dfs(tv, i)
return count
print((dfs([0] * n, 1))) | p03805 |
# 頂点および辺の数を入力
N, M = list(map(int, input().split()))
# 辺のリストを作成
list_edge = [[] for _ in range(N + 1)]
for _ in range(M):
a, b = list(map(int, input().split()))
list_edge[a].append(b)
list_edge[b].append(a)
# パス(リスト)のリストを初期化
list_path = [[1]]
# パスが存在する、かつパスの長さが頂点の数未満である場合に繰り返し
while list_path != [] and len(list_path[0]) < N:
# パスのリストから先頭のパスを取り出す
path = list_path.pop(0)
# パスの最後尾の頂点から訪問可能な頂点について、、
for node in list_edge[path[-1]]:
# その頂点にまだ訪問していない場合、、
if node not in path:
# パスのリストに新たなパスを加える
list_path.append(path + [node])
# パスの数を出力する
print((len(list_path))) | # 頂点および辺の数を入力
N, M = list(map(int, input().split()))
# 辺のリストを作成
list_edge = [[] for _ in range(N + 1)]
for _ in range(M):
a, b = list(map(int, input().split()))
list_edge[a].append(b)
list_edge[b].append(a)
# パスの数を返す関数を定義
def count_path(node, path, list_edge, N):
# パスの数を初期化
count = 0
# 全ての頂点を訪問した場合、、
if len(path) == N:
# パスの数に1を加える
count += 1
# 全ての頂点を訪問していない場合、、
else:
# 現在の頂点から訪問できる各頂点について、、
for next_node in list_edge[node]:
# その頂点にまだ訪問していない場合、、
if next_node not in path:
# 再帰
count += count_path(next_node, path + [next_node], list_edge, N)
# パスの本数を返す
return count
# パスの本数を出力する
print((count_path(1, [1], list_edge, N))) | p03805 |
import os,re,sys,operator
from collections import Counter,deque
from operator import itemgetter
from itertools import accumulate,combinations,groupby
from sys import stdin,setrecursionlimit
from copy import deepcopy
import heapq
setrecursionlimit(10**6)
def dfs(now,depth):
global used
global gragh
global n
ans=0
if used[now]:
return 0
if depth==n:
return 1
used[now]=1
for i in range(n):
if gragh[now][i]:
ans+=dfs(i,depth+1)
used[now]=0
return ans
n,m=list(map(int,stdin.readline().rstrip().split()))
gragh=[[0]*n for _ in range(n)]
for i in range(m):
a,b=list(map(int,stdin.readline().rstrip().split()))
gragh[a-1][b-1]=gragh[b-1][a-1]=1
used=[0]*n
print((dfs(0,1))) | import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
n,m=list(map(int,input().split()))
G=[[False]*n for _ in range(n)]
used=[False]*n
def dfs(now,depth):
if used[now]:
return 0
if n==depth:
return 1
used[now]=True
ans=0
for i in range(n):
if G[now][i]:
ans+=dfs(i,depth+1)
used[now]=False
return ans
for _ in range(m):
a,b=list(map(int,input().split()))
G[a-1][b-1]=True
G[b-1][a-1]=True
print((dfs(0,1))) | p03805 |
num_ver, num_edge = list(map(int,input().split()))
# 隣接行列
graph_mat = [[0]*num_ver for _ in range(num_ver)]
for i in range(num_edge):
start, goal = list(map(int,input().split()))
start -= 1
goal -= 1
graph_mat[start][goal] = 1
graph_mat[goal][start] = 1
visited = [0] * num_ver
#再帰関数
def dfs(now, depth):
if visited[now]:
return 0
if depth == num_ver - 1:
return 1
visited[now] = 1
total_paths = 0
# 「同じ深さの処理」=場合わけ
for i in range(num_ver):
if graph_mat[now][i]:
total_paths += dfs(i, depth + 1)
visited[now] = 0
return total_paths
print((dfs(0, 0)))
| num_ver, num_edge = list(map(int,input().split()))
# 隣接行列
graph_mat = [[0]*num_ver for _ in range(num_ver)]
for i in range(num_edge):
start, goal = list(map(int,input().split()))
start -= 1
goal -= 1
graph_mat[start][goal] = 1
graph_mat[goal][start] = 1
visited = [0] * num_ver
def dfs(now, depth):
if visited[now]:
return 0
if depth == num_ver - 1:
return 1
visited[now] = 1
num_path = 0
for ver in range(num_ver):
if graph_mat[now][ver]:
num_path += dfs(ver, depth + 1)
# 別の一筆書きの道として探索されることを考慮、もちろん頂点1についてはこれは意味ない
visited[now] = 0
return num_path
print((dfs(0,0))) | p03805 |
from itertools import permutations
n_ver,n_edge = list(map(int,input().split()))
path_mat = [[0]*n_ver for _ in range(n_ver)]
for i in range(n_edge):
a,b = list(map(int,input().split()))
a -= 1
b -= 1
path_mat[a][b] = 1
path_mat[b][a] = 1
ans = 0
vers = [i for i in range(n_ver)]
for path in permutations(vers):
if path[0] != 0:
continue
can = True
for i in range(n_ver-1):
from_ = path[i]
to = path[i+1]
if not path_mat[from_][to]:
can = False
break
if can:
ans += 1
print(ans)
| import sys
sys.setrecursionlimit(10**7)
n_ver, n_edge = list(map(int,input().split()))
ad_ls = [[] for _ in range(n_ver)]
for i in range(n_edge):
a,b = list(map(int,input().split()))
a -= 1
b -= 1
ad_ls[a].append(b)
ad_ls[b].append(a)
done_ls = [0] * n_ver
def dfs(ver):
done_ls[ver] = 1
num = 0
if done_ls == [1] * n_ver:
done_ls[ver] = 0
return 1
for nex in ad_ls[ver]:
if done_ls[nex]:
continue
num += dfs(nex)
done_ls[ver] = 0
return num
print((dfs(0)))
| p03805 |
import itertools
n,m = list(map(int,input().split()))#頂点の数、辺の数
graph = [[False for i in range(n)] for j in range(n)]
for i in range(m):
a,b = list(map(int,input().split()))
a -= 1
b -= 1
graph[a][b] = True
graph[b][a] = True
ans = 0
for i in itertools.permutations(list(range(n))):
if i[0] != 0:
continue
visited = [0]*n
visited[0] += 1
for j in range(n):
if j == n-1:
if 0 not in visited:
ans += 1
break
if graph[i[j]][i[j+1]] == True:
visited[i[j+1]] += 1
print(ans)
| import itertools
n,m = list(map(int,input().split()))
path = [[] for i in range(n+1)]
for i in range(m):
a,b = list(map(int,input().split()))
path[a].append(b)
path[b].append(a)
ans = 0
l = [i for i in range(2,n+1)]
for v in itertools.permutations(l,n-1):
flag = True
if v[0] not in path[1]:
flag = False
continue
for k in range(1,n-1):
if v[k] not in path[v[k-1]]:
flag = False
continue
if flag:
ans += 1
print(ans)
| p03805 |
import itertools
N,M=list(map(int,input().split()))
route=[list(map(int,input().split())) for _ in range(M)]
candidate=list(itertools.permutations(list(range(1,N+1))))
ans=0
for c in candidate:
if c[0]==1:
for i in range(N-1):
l=sorted([c[i], c[i+1]])
if l not in route:
break
else:
ans+=1
print(ans)
| import itertools
N, M = list(map(int, input().split()))
G = {k: set() for k in range(N+1)}
for _ in range(M):
a, b = list(map(int, input().split()))
# 無向グラフ
G[a].add(b)
G[b].add(a)
ans = 0
for p in itertools.permutations(list(range(2, N+1))):
c = 1
for n in p:
if n not in G[c]:
break
c = n
else:
ans += 1
print(ans)
| p03805 |
from collections import deque
N, M = list(map(int, input().split()))
V = []
for i in range(M):
a, b = list(map(int, input().split()))
V.append((a-1, b-1))
def bfs(G):
visited = [False] * N
visited[0] = True
que = deque([(0, -1, 0)])
r = 0
while que:
ci, p, d = que.popleft()
for ni in G[ci]:
if visited[ni] is False:
visited[ni] = True
que.append((ni, ci, d+1))
r = max(r, d+1)
return r
ans = 0
for i in range(2 ** M):
if bin(i).count('1') != N-1:
continue
else:
G = {k: [] for k in range(N)}
for j in range(M): # このループが一番のポイント
if ((i >> j) & 1): # 順に右にシフトさせ最下位bitのチェックを行う
(a, b) = V[j]
G[a].append(b)
G[b].append(a)
if bfs(G) == N-1:
ans += 1
print(ans)
| import sys
sys.setrecursionlimit(1000000)
N, M = list(map(int, input().split()))
G = {k: [] for k in range(N)}
for _ in range(M):
a, b = list(map(int, input().split()))
# 無向グラフ
G[a-1].append(b-1)
G[b-1].append(a-1)
visited = [False]*N
visited[0] = True
def dfs(v):
if all(visited):
return 1
r = 0
for nv in G[v]:
if visited[nv] is False:
visited[nv] = True
r += dfs(nv)
visited[nv] = False
return r
print((dfs(0)))
| p03805 |
import sys
sys.setrecursionlimit(1000000)
N,M = list(map(int, input().split()))
P = [list(map(int, input().split())) for _ in range(M)]
vis_N = [-1]*(N+1)
count = 0
vis_N[1] = 1
def search(a):
global count,vis_N,vis_Nij
#print(count,vis_N)
if sum(vis_N)+1 == N:
count = count + 1
return# count#print(count,"A",i)
for i in range(M):
if (P[i][0] == a and vis_N[P[i][1]] == -1) or (P[i][1] == a and vis_N[P[i][0]] == -1):
if P[i][0] == a:
nxt = P[i][1]
else:
nxt = P[i][0]
#vis_N[a] = 1
vis_N[nxt] = 1
search(nxt)
vis_N[nxt] = -1
return# count
search(1)
print(count) | N, M = list(map(int, input().split()))
adj_matrix = [[0]* N for _ in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
adj_matrix[a-1][b-1] = 1
adj_matrix[b-1][a-1] = 1
def dfs(v, used):
if not False in used:
return 1
ans = 0
for i in range(N):
if not adj_matrix[v][i]:
continue
if used[i]:
continue
used[i] = True
ans += dfs(i, used)
used[i] = False
return ans
used = [False] * N
used[0] = True
print((dfs(0, used))) | p03805 |
# 基本課題 3.経路探索の解を求める
#
# 5 つの地点 0 ~ 4 を結ぶ道路網が図のようにある ( 図は授業支援システム参照 )
# 始点を 0 とし終点を 4 とした時、0 から 4 に至る経路をすべて求めなさい。
# ただし、同じ地点を2度通ってはいけない
#
# -*- coding: utf-8 -*-
ANS2=[] #0から4までの経路列挙(2次元配列)
#引数
#G:道路網を表す2次元配列(隣接リスト)
#LT:今のところの経路(だんだん広げていく)(最初は[[0]])
#返り値
#広げられなくなるまで広げた経路
#副作用
#ANS2を更新
#ANS2:0から4までの経路
def loot(G,LT):
if LT==[]:
return []
else:
ANS=[] #今の地点から一回広げた時点での経路
for i in range(len(LT)):
for j in range(len(G[LT[i][-1]])):
if not(G[LT[i][-1]][j] in LT[i]):
TMP=LT[i]
ANS.append(TMP+[G[LT[i][-1]][j]])
else:
if not LT[i] in ANS2:
ANS2.append(LT[i])
return loot(G,ANS)
#2次元リストを標準出力
def print_list(lst):
for i in range(len(lst)):
for j in range(len(lst[i])):
print(ANS2[i][j],end=' ')
print('')
N,M=map(int,input().split())
G=[[] for i in range(N)]
for i in range(M):
a,b=map(int,input().split())
a-=1
b-=1
G[a].append(b)
G[b].append(a)
loot(G,[[0]])
cnt=0
for i in ANS2:
if len(i)==N:
cnt+=1
print(cnt)
| # 基本課題 3.経路探索の解を求める
#
# 5 つの地点 0 ~ 4 を結ぶ道路網が図のようにある ( 図は授業支援システム参照 )
# 始点を 0 とし終点を 4 とした時、0 から 4 に至る経路をすべて求めなさい。
# ただし、同じ地点を2度通ってはいけない
#
# -*- coding: utf-8 -*-
ANS2=[] #0から4までの経路列挙(2次元配列)
#引数
#G:道路網を表す2次元配列(隣接リスト)
#LT:今のところの経路(だんだん広げていく)(最初は[[0]])
#返り値
#広げられなくなるまで広げた経路
#副作用
#ANS2を更新
#ANS2:0から4までの経路
def loot(G,LT,N):
if LT==[]:
return []
else:
ANS=[] #今の地点から一回広げた時点での経路
for i in range(len(LT)):
for j in range(len(G[LT[i][-1]])):
if not(G[LT[i][-1]][j] in LT[i]):
TMP=LT[i]
ANS.append(TMP+[G[LT[i][-1]][j]])
else:
if not LT[i] in ANS2:
if len(LT[i])==N:
ANS2.append(LT[i])
return loot(G,ANS,N)
#2次元リストを標準出力
def print_list(lst):
for i in range(len(lst)):
for j in range(len(lst[i])):
print(ANS2[i][j],end=' ')
print('')
N,M=map(int,input().split())
G=[[] for i in range(N)]
for i in range(M):
a,b=map(int,input().split())
a-=1
b-=1
G[a].append(b)
G[b].append(a)
loot(G,[[0]],N)
cnt=0
print(len(ANS2))
| p03805 |
import copy
N, M = [ int(x) for x in input().split()]
class Node:
def __init__(self, id):
self.id = id
self.path = []
self.passed = False
def __str__(self):
return "id: " + str(self.id) + " path: " + str(self.path) + " passed: " + str(self.passed)
nodes = []
for i in range(N):
nodes.append(Node(i))
for i in range(M):
from_id, to_id = [ int(x) - 1 for x in input().split()]
nodes[from_id].path.append(to_id)
nodes[to_id].path.append(from_id)
def if_all_passed(nodes_current):
for node in nodes_current:
if not node.passed:
return False
return True
def go_child(id_new, nodes_current):
nodes_current[id_new].passed = True
if if_all_passed(nodes_current):
return 1
count = 0
for i in nodes[id_new].path:
if not nodes_current[i].passed:
count += go_child(i, copy.deepcopy(nodes_current))
return count
count = go_child(0, nodes)
print(count)
| import copy
N, M = [ int(x) for x in input().split() ]
class Node:
def __init__(self, id):
self.id = id
self.path = []
def __str__(self):
return "id: " + str(self.id) + " path: " + str(self.path)
nodes = []
for i in range(N):
nodes.append(Node(i))
for i in range(M):
from_id, to_id = [ int(x) - 1 for x in input().split() ]
nodes[from_id].path.append(to_id)
nodes[to_id].path.append(from_id)
def if_all_passed(passed_nodes):
if len(passed_nodes) == N:
return True
else:
return False
def go_child(id_new, passed_nodes):
passed_nodes.append(id_new)
if if_all_passed(passed_nodes):
return 1
count = 0
for i in nodes[id_new].path:
if not i in passed_nodes:
count += go_child(i, copy.deepcopy(passed_nodes))
return count
count = go_child(0, [])
print(count)
| p03805 |
import itertools
n, m=list(map(int, input().split()))
ab=[set(map(int, input().split())) for _ in range(m)]
root=list(itertools.permutations(ab, n-1))
cnt=0
for r in root:
trace=[i+1 for i in range(n)]
other=1
for i in range(0, n-1):
if other in r[i]:
try:
trace.remove(other)
except ValueError:
break
other=list(r[i]-{other})[0]
continue
else: break
try:
trace.remove(other)
except ValueError:
pass
if trace==[]:
cnt+=1
print(cnt) | N, M = list(map(int, input().split()))
adj_matrix = [[0]* N for _ in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
adj_matrix[a-1][b-1] = 1
adj_matrix[b-1][a-1] = 1
def dfs(v, used):
if not False in used:
return 1
ans = 0
for i in range(N):
if not adj_matrix[v][i]:
continue
if used[i]:
continue
used[i] = True
ans += dfs(i, used)
used[i] = False
return ans
used = [False] * N
used[0] = True
print((dfs(0, used))) | p03805 |
import itertools
n, m = list(map(int, input().split()))
path = [[False] * n for i in range(n)]
for i in range(m):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
path[a][b] = True
path[b][a] = True
ans = 0
for i in itertools.permutations(list(range(n)), n):
# 頂点1が始点
if i[0] == 0:
for j in range(n):
if j == n - 1:
ans += 1
break
if not path[i[j]][i[j + 1]]:
break
print(ans)
| def main():
N, M = list(map(int, input().split()))
matrix = [[0] * N for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
matrix[a-1][b-1] = 1
matrix[b-1][a-1] = 1
def dfs(v, used):
if False not in used:
return 1
ans = 0
for i in range(N):
if not matrix[v][i]:
continue
if used[i]:
continue
used[i] = True
ans += dfs(i, used)
used[i] = False
return ans
used = [False] * N
used[0] = True
print((dfs(0, used)))
if __name__ == '__main__':
main()
| p03805 |
import itertools
n, m = list(map(int, input().split()))
v = []
for i in range(m):
tpl = tuple(map(int, input().split()))
v.append(tpl)
v.append((tpl[1], tpl[0]))
perms = list(itertools.permutations(v, n-1))
c = 0
for i in perms:
if i[0][0] != 1:
continue
visited = []
for j in range(len(i)-1):
if i[j][1] != i[j+1][0]:
break
visited.append(i[j][0])
if i[j+1][1] in visited:
break
else:
c += 1
print(c)
| import itertools
n, m = list(map(int, input().split()))
v = []
for i in range(m):
tpl = tuple(map(int, input().split()))
v.append(tpl)
v.append((tpl[1], tpl[0]))
perms = list(itertools.permutations(list(range(1, n+1))))
c = 0
for i in perms:
if i[0] != 1:
continue
for j in range(len(i)-1):
if (i[j], i[j+1]) not in v:
break
else:
c += 1
print(c)
| p03805 |
from itertools import permutations
n,m = list(map(int,input().split()))
D = [[0]*n for i in range(n)]
for i in range(m):
a,b = list(map(int,input().split()))
D[a-1][b-1] = 1
D[b-1][a-1] = 1
cnt = 0
for a in permutations(list(range(n))):
if a[0] != 0:
break
tmp = 1
for i in range(n-1):
tmp = tmp * D[a[i]][a[i+1]]
cnt += tmp
print(cnt) | n,m = list(map(int, input().split()))
D = [list() for i in range(n)]
for i in range(m):
a,b = list(map(int,input().split()))
D[a-1].append(b-1)
D[b-1].append(a-1)
d = [0]*n
d[0] = 1
cnt = 0
def dfs(x):
global cnt
if all(d):
cnt += 1
return
for i in D[x]:
if d[i] == 0:
d[i] = 1
dfs(i)
d[i] = 0
dfs(0)
print(cnt) | p03805 |
def main():
N, M = (int(i) for i in input().split())
edge = [set() for _ in range(N)]
for i in range(M):
a, b = (int(i) for i in input().split())
edge[a-1].add(b-1)
edge[b-1].add(a-1)
from itertools import permutations
ans = 0
for p in permutations(list(range(1, N))):
u = 0
for v in p:
if v not in edge[u]:
break
u = v
else:
ans += 1
print(ans)
if __name__ == '__main__':
main()
| def main():
import sys
input = sys.stdin.buffer.readline
from itertools import permutations
N, M = (int(i) for i in input().split())
edge = [[] for _ in range(N)]
for i in range(M):
a, b = (int(i) for i in input().split())
edge[a-1].append(b-1)
edge[b-1].append(a-1)
ans = 0
for p in permutations(list(range(1, N))):
v = 0
for nv in p:
if nv in edge[v]:
v = nv
else:
break
else:
ans += 1
print(ans)
if __name__ == '__main__':
main()
| p03805 |
import copy
N, M = list(map(int,input().split()))
E = [list(map(int, input().split())) for _ in range(M)]
def dfs(flg, E, i):
q = []
for e in E:
if e[0] == i:
if flg[e[1]-1] == 0:
q.append(e[1])
if e[1] == i:
if flg[e[0]-1] == 0:
q.append(e[0])
if len(q) == 0:
if flg.count(0) == 0:
return 1
else:
return 0
ans = 0
for n in q:
temp = copy.deepcopy(flg)
temp[n-1] = 1
ans += dfs(temp, E, n)
return ans
flg = [0 for _ in range(N)]
flg[0] = 1
print((dfs(flg, E, 1))) | N, M = list(map(int, input().split()))
E = [[] for _ in range(N)]
for _ in range(M):
ta, tb = list(map(int, input().split()))
E[ta-1].append(tb-1)
E[tb-1].append(ta-1)
def next_permutation(out, cnt, flg):
if cnt == N:
for i in range(N-1):
if out[i+1] not in E[out[i]]:
return 0
return 1
ans = 0
for i in range(N):
if flg[i] == 0:
out.append(i)
flg[i] = 1
ans += next_permutation(out, cnt+1, flg)
out.pop()
flg[i] = 0
return ans
perm = [0]
cnt = 1
flg = [0 for _ in range(N)]
flg[0] = 1
answer = next_permutation(perm, cnt, flg)
print(answer) | p03805 |
import itertools
N, M = list(map(int, input().split()))
ab = []
for _ in range(M):
a, b = list(map(int, input().split()))
ab.append({a-1, b-1})
ans = 0
for v in itertools.permutations(list(range(1, N))):
ok = True
a = 0
for b in v:
if {a, b} not in ab:
ok = False
break
a = b
if ok:
ans += 1
print(ans)
| N, M = list(map(int, input().split()))
ab = [[] for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
ab[a-1].append(b-1)
ab[b-1].append(a-1)
ans = 0
def dfs(x, visited):
global ans
if len(visited) == N:
ans += 1
return
for b in ab[x]:
if b not in visited:
dfs(b, visited + [b])
return
dfs(0, [0])
print(ans)
| p03805 |
import copy
import sys
sys.setrecursionlimit(10**7)
N, M = list(map(int, input().split()))
edges = [[] for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
edges[a - 1].append(b - 1)
edges[b - 1].append(a - 1)
ans = 0
def dfs(start,path):
next_path = copy.copy(path)
global ans
next_path.append(start)
if len(next_path) == N:
ans += 1
return
for i in edges[start]:
if i not in next_path:
dfs(i,next_path)
dfs(0,[])
print(ans) | def dfs(start,path):
res = 0
path.append(start)
if len(path) == N:
res += 1
return res
for i in graph[start]:
if i not in path:
res += dfs(i,path)
path.pop()
return res
N, M = list(map(int, input().split()))
graph = [[] for _ in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
graph[a-1].append(b-1)
graph[b-1].append(a-1)
print((dfs(0,[]))) | p03805 |
import sys
from itertools import permutations
def debug(x, table):
for name, val in table.items():
if x is val:
print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
return None
cnt = 0
def dfs(N, Adj, p, pos, mask):
global cnt
if pos == N:
for i in range(N - 1):
if not Adj[p[i]][p[i + 1]]:
break
else:
cnt += 1
return None
for i in range(N):
if mask & (1 << i):
p[pos] = i
dfs(N, Adj, p, pos + 1, (mask ^ (1 << i)))
return None
def solve():
global cnt
cnt = 0
N, M = map(int, input().split())
Adj = [[0]*N for i in range(N)]
for i in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
Adj[a][b] = 1
Adj[b][a] = 1
p = list(range(N))
dfs(N, Adj, p, 1, (2 << N) - 1 - 1)
print(cnt)
if __name__ == '__main__':
solve()
| import sys
from itertools import permutations
def debug(x, table):
for name, val in table.items():
if x is val:
print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
return None
def do_dp(N, Adj):
univ = 2**N - 1
dp = [[0]*N for i in range(univ + 1)]
dp[1][0] = 1
for S in range(2, univ + 1):
for v in range(N):
S2 = S & (univ ^ (1 << v))
for u in range(N):
if ((1 << u) & S2) and Adj[u][v]:
dp[S][v] += dp[S2][u]
# debug(dp, locals())
ans = sum(dp[univ][u] for u in range(1, N))
return ans
def solve():
N, M = map(int, input().split())
Adj = [[0]*N for i in range(N)]
for i in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
Adj[a][b] = 1
Adj[b][a] = 1
ans = do_dp(N, Adj)
print(ans)
if __name__ == '__main__':
solve()
| p03805 |
import sys
from itertools import permutations
def debug(x, table):
for name, val in table.items():
if x is val:
print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
return None
def do_dp(N, Adj):
univ = 2**N - 1
dp = [[0]*N for i in range(univ + 1)]
dp[1][0] = 1
for S in range(2, univ + 1):
for v in range(N):
S2 = S & (univ ^ (1 << v))
for u in range(N):
if ((1 << u) & S2) and Adj[u][v]:
dp[S][v] += dp[S2][u]
# debug(dp, locals())
ans = sum(dp[univ][u] for u in range(1, N))
return ans
def solve():
N, M = map(int, input().split())
Adj = [[0]*N for i in range(N)]
for i in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
Adj[a][b] = 1
Adj[b][a] = 1
ans = do_dp(N, Adj)
print(ans)
if __name__ == '__main__':
solve()
| import sys
def debug(x, table):
for name, val in table.items():
if x is val:
print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
return None
def do_dp(N, Adj):
univ = 2**(N-1) - 1
dp = [[0]*(N-1) for i in range(univ + 1)]
for u in range(N - 1):
if Adj[0][u+1]:
dp[1<<u][u] = 1
for S in range(univ + 1):
for v in range(N - 1):
S2 = S & (univ ^ (1 << v))
for u in range(N):
if ((1 << u) & S2) and Adj[u+1][v+1]:
dp[S][v] += dp[S2][u]
# debug(dp, locals())
ans = sum(dp[univ][u] for u in range(N - 1))
return ans
def solve():
N, M = map(int, input().split())
Adj = [[0]*N for i in range(N)]
for i in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
Adj[a][b] = 1
Adj[b][a] = 1
ans = do_dp(N, Adj)
print(ans)
if __name__ == '__main__':
solve()
| p03805 |
# -*- coding: utf-8 -*-
from collections import deque
N, M = list(map(int, input().split()))
Ms = {i:set() for i in range(1, N + 1)}
for _ in range(M):
a, b = list(map(int, input().split()))
Ms[a].add(b)
Ms[b].add(a)
all = set(range(1, N + 1))
q = deque()
q.append((1, [1]))
ans = 0
while q:
n, v = q.popleft()
if set(v) == all:
ans += 1
continue
for to in Ms[n]:
if not to in v:
q.append((to, v + [to]))
print(ans)
| N, M = list(map(int, input().split()))
G = [[] for _ in range(N)]
for _ in range(M):
A, B = list(map(int, input().split()))
G[A - 1].append(B - 1)
G[B - 1].append(A - 1)
path, ans = [[0]], 0
while len(path) > 0:
p = path.pop()
if len(p) == N:
ans += 1
else:
for g in G[p[-1]]:
if not g in p:
path.append(p + [g])
print(ans)
| p03805 |
import itertools as it
import sys
N, M = list(map(int, input().split()))
if N==0 or M==0:
print((0))
sys.exit()
a=[]
for i in range(M):
x,y=list(map(int,input().split()))
a.append([x,y])
a.append([y,x])
ans=0
for e in it.permutations(list(range(N))):
if e[0]!=0:
break
count=1
for j in range(N-1):
if [e[j]+1,e[j+1]+1] in a:
count*=1
else:
count*=0
break
ans+=count
print(ans) | import itertools as it
import sys
N, M = list(map(int, input().split()))
a=[]
for i in range(M):
x,y=list(map(int,input().split()))
a.append([x,y])
a.append([y,x])
ans=0
for e in it.permutations(list(range(N))):
if e[0]!=0:
break
count=1
for j in range(N-1):
if [e[j]+1,e[j+1]+1] in a:
count*=1
else:
count*=0
break
ans+=count
print(ans) | p03805 |
n,m=list(map(int,input().split()))
edges=[[] for i in range(n)]
for i in range(m):
s,t = list(map(int,input().split()))
edges[s-1].append(t-1)
edges[t-1].append(s-1)
cnt =[0]
def dfs(V,s):
V[s]=1
if sum(V)==n:
cnt[0]+=1
else:
for adj in edges[s]:
if V[adj] == 0:
dfs(V[:adj] + [1] + V[adj + 1:], adj)
dfs([0] * n, 0)
print((cnt[0]))
| n,m=list(map(int,input().split()))
edges=[[] for i in range(n)]
for i in range(m):
s,t = list(map(int,input().split()))
edges[s-1].append(t-1)
edges[t-1].append(s-1)
cnt =0
V=[0]*n
def dfs(V,s):
global cnt
V=V[:]
V[s]=1
if sum(V)==n:
cnt+=1
else:
for v in edges[s]:
if V[v]==0:
dfs(V,v)
# print(V)
dfs(V,0)
print(cnt) | p03805 |
n,m=list(map(int,input().split()))
edges=[[] for i in range(n)]
for i in range(m):
s,t = list(map(int,input().split()))
edges[s-1].append(t-1)
edges[t-1].append(s-1)
cnt =0
V=[0]*n
def dfs(V,s):
global cnt
V=V[:]
V[s]=1
if sum(V)==n:
cnt+=1
else:
for v in edges[s]:
if V[v]==0:
dfs(V,v)
# print(V)
dfs(V,0)
print(cnt) | n,m=list(map(int,input().split()))
edges=[[0]*n for i in range(n)]
for i in range(m):
a,b=list(map(int,input().split()))
edges[a-1].append(b-1)
edges[b-1].append(a-1)
visited=[False]*n
count=0
def dfs(u,visited):
global count
visited=visited[:]
visited[u]=True
if all(visited):
count+=1
return
for v in edges[u]:
if not visited[v]:
dfs(v,visited)
return False
dfs(0,visited)
print(count) | p03805 |
import array
import itertools
from collections import defaultdict, deque
def log(s):
# print("| " + str(s), file=sys.stderr)
pass
def output(x):
print(x, flush=True)
def input_ints():
return map(int, input().split())
def solve():
num_nodes, num_edges = tuple(input_ints())
edges = [tuple(input_ints()) for _ in range(num_edges)]
navigatility = defaultdict(lambda: [])
for e in edges:
navigatility[e[0]].append(e[1])
navigatility[e[1]].append(e[0])
queue = deque()
queue.append([1])
result = []
while queue:
path = queue.popleft()
if len(path) == num_nodes:
result.append(path)
else:
n = path[-1]
for m in navigatility[n]:
if m not in path:
queue.append(path + [m])
return result
def main():
print(len(solve()))
main()
| import array
import itertools
from collections import defaultdict, deque
def log(s):
# print("| " + str(s), file=sys.stderr)
pass
def output(x):
print(x, flush=True)
def input_ints():
return map(int, input().split())
def solve():
num_nodes, num_edges = tuple(input_ints())
edges = [tuple(input_ints()) for _ in range(num_edges)]
navigability = defaultdict(lambda: [])
for e in edges:
navigability[e[0]].append(e[1])
navigability[e[1]].append(e[0])
def solve1(path, result):
if len(path) == num_nodes:
result.append(path)
return
for m in navigability[path[-1]]:
if m not in path:
solve1(path + [m], result)
return result
return solve1([1], [])
def main():
print(len(solve()))
main()
| p03805 |
from itertools import permutations
N, M = list(map(int, input().split()))
edges = []
for i in range(M):
a, b = list(map(int, input().split()))
edges.append([a-1, b-1])
mat = [[0]*N for _ in range(N)]
for s, g in edges:
mat[s][g] = 1
mat[g][s] = 1
P = permutations(list(range(N)))
ans = 0
for route in P:
if route[0] != 0:
continue
else:
vis = 0
for s, g in zip(route, route[1:]):
if mat[s][g] == 1:
vis += 1
if vis == N-1:
ans += 1
continue
else:
break
print(ans)
| def bit_dp(N, Adj):
dp = [[0]*N for i in range(1 << N)]
#dp[{0},0] = 1
dp[1][0] = 1
for S in range(1 << N):
for v in range(N):
# v がSに含まれていないときはパス
if (S & (1 << v)) == 0:
continue
#sub = S - {v}
sub = S ^ (1 << v)
for u in range(N):
# sub に uが含まれていて、かつ uとvがへんで結ばれている
if (sub & (1 << u)) and (Adj[u][v]):
dp[S][v] += dp[sub][u]
ans = sum(dp[(1 << N) - 1][u] for u in range(1, N))
return ans
def main():
N, M = list(map(int, input().split()))
Adj = [[False]*N for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
Adj[a-1][b-1] = 1
Adj[b-1][a-1] = 1
ans = bit_dp(N, Adj)
print(ans)
if __name__ == '__main__':
main()
| p03805 |
import itertools
N, M = list(map(int, input().split()))
adj_matrix = [[0]*N for _ in range(N)]
# 隣接行列を作る
for i in range(M):
a, b = list(map(int, input().split()))
adj_matrix[a-1][b-1] = 1
adj_matrix[b-1][a-1] = 1
cnt = 0
for each in itertools.permutations(list(range(N))):
if each[0] != 0: # 始点は1でないといけないから
break
factor = 1
for i in range(N-1):
factor *= adj_matrix[each[i]][each[i+1]]
cnt += factor
print(cnt) | N, M = list(map(int, input().split()))
adj_matrix = [[0]*N for _ in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
adj_matrix[a-1][b-1] = 1
adj_matrix[b-1][a-1] = 1
def dfs(v, used):
if not False in used:
return 1
ans = 0
for i in range(N):
if not adj_matrix[v][i]:
continue
if used[i]:
continue
used[i] = True
ans += dfs(i, used)
used[i] = False
return ans
used = [False] * N
used[0] = True
print((dfs(0, used))) | p03805 |
N, M = list(map(int, input().split()))
adj_matrix = [[0]*N for _ in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
adj_matrix[a-1][b-1] = 1
adj_matrix[b-1][a-1] = 1
def dfs(v, used):
if not False in used:
return 1
ans = 0
for i in range(N):
if not adj_matrix[v][i]:
continue
if used[i]:
continue
used[i] = True
ans += dfs(i, used)
used[i] = False
return ans
used = [False] * N
used[0] = True
print((dfs(0, used))) | N, M = list(map(int, input().split()))
g = [[] for i in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
g[a-1].append(b-1)
g[b-1].append(a-1)
memo = {}
All_used = (1 << N) - 1
def dfs(v, used):
if used == All_used:
return 1
key = (v, used)
if key in memo:
return memo[key]
ans = 0
for u in g[v]:
if (used >> u) & 1 ==1:
continue
used ^= (1 << u)
ans += dfs(u, used)
used ^= (1 << u)
memo[key] = ans
return ans
print((dfs(0, 1))) | p03805 |
from collections import deque
from copy import deepcopy as dc
import sys
def main():
input = sys.stdin.readline
n, m = list(map(int, input().split()))
ab = [list(map(int, input().split())) for i in range(m)]
g = [[] for i in range(n+1)]
for i in ab:
g[i[0]].append(i[1])
g[i[1]].append(i[0])
que = deque()
que.append([1,-1,0,set([1])])
ans = 0
while que:
v, p, cnt, check = que.popleft()
if cnt >= n - 1:
if len(check) == n:
ans += 1
continue
for nv in g[v]:
if nv == p:
continue
a = dc(check)
a.add(nv)
que.append([nv, v, cnt+1, a])
print(ans)
if __name__ == "__main__":
main()
| from collections import deque
from copy import copy as dc
import sys
def main():
input = sys.stdin.readline
n, m = list(map(int, input().split()))
ab = [list(map(int, input().split())) for i in range(m)]
g = [[] for i in range(n+1)]
for i in ab:
g[i[0]].append(i[1])
g[i[1]].append(i[0])
que = deque()
que.append([1,-1,0,set([1])])
ans = 0
while que:
v, p, cnt, check = que.popleft()
if cnt >= n - 1:
if len(check) == n:
ans += 1
continue
for nv in g[v]:
if nv == p:
continue
a = dc(check)
a.add(nv)
que.append([nv, v, cnt+1, a])
print(ans)
if __name__ == "__main__":
main()
| p03805 |
from collections import deque
from copy import copy as dc
import sys
def main():
input = sys.stdin.readline
n, m = list(map(int, input().split()))
ab = [list(map(int, input().split())) for i in range(m)]
g = [[] for i in range(n+1)]
for i in ab:
g[i[0]].append(i[1])
g[i[1]].append(i[0])
que = deque()
que.append([1,-1,0,set([1])])
ans = 0
while que:
v, p, cnt, check = que.popleft()
if cnt >= n - 1:
if len(check) == n:
ans += 1
continue
for nv in g[v]:
if nv == p:
continue
a = dc(check)
a.add(nv)
que.append([nv, v, cnt+1, a])
print(ans)
if __name__ == "__main__":
main()
| import sys
sys.setrecursionlimit(4100000)
def Dfs(G, v, n, visited):
all_visited = True
for i in range(n):
if visited[i] == False:
all_visited = False
if all_visited:
return 1
ret = 0
for i in range(n):
if not G[v][i]:
continue
if visited[i]:
continue
visited[i] = True
ret += Dfs(G, i, n, visited)
visited[i] = False
return ret
def main():
input = sys.stdin.readline
n, m = list(map(int, input().split()))
e = [list(map(int, input().split())) for i in range(m)]
g = [[False for j in range(n)] for i in range(n)]
for i, j in e:
g[i-1][j-1] = True
g[j-1][i-1] = True
visited = [False for i in range(n)]
visited[0] = True
print((Dfs(g, 0, n, visited)))
if __name__ == "__main__":
main()
| p03805 |
from itertools import permutations
from copy import deepcopy
N,M = [int(i) for i in input().split()]
links = [[int(i) for i in input().split()] for _ in range(M)]
ans = 0
for path in permutations(list(range(2,N+1))):
l = deepcopy(links)
p_node = 1
for n_node in path:
if sorted([p_node,n_node]) in l:
l.pop(l.index(sorted([p_node,n_node])))
p_node = n_node
continue
else:
break
else:
ans += 1
print(ans)
| from itertools import permutations
from copy import deepcopy
N,M = [int(i) for i in input().split()]
links = set([input().strip() for _ in range(M)])
ans = 0
for path in permutations(list(range(2,N+1))):
l = deepcopy(links)
p_node = 1
for n_node in path:
e_l = " ".join([str(s) for s in sorted([p_node,n_node])])
if e_l in l:
l.remove(e_l)
p_node = n_node
continue
else:
break
else:
ans += 1
print(ans) | p03805 |
import itertools
n,m=list(map(int,input().split()))
path=[[False]*n for i in range(n)]
for i in range(m):
a,b=list(map(int,input().split()))
a-=1
b-=1
path[a][b]=True
path[b][a]=True
ans=0;
for i in itertools.permutations(list(range(n)),n):
if i[0]==0:
for j in range(n):
if j==n-1:
ans+=1
break
if not path[i[j]][i[j+1]]:
break
print(ans) | def dfs(a,count,seen):
nseen=seen[:]
ans=0
nseen[a] = 1;
if count==n-1:
return 1
else:
for i in g[a]:
if not seen[i]:
ans+=dfs(i,count+1,nseen)
return ans
n,m=list(map(int,input().split()))
g=[[]*n for i in range(n)]
for i in range(m):
a,b=list(map(int,input().split()))
a-=1
b-=1
g[a].append(b)
g[b].append(a)
seen=[0]*n
print((dfs(0,0,seen)))
| p03805 |
N, M = list(map(int, input().split()))
E = [[] for i in range(M)]
for i in range(M):
E[i] = [int(x) - 1 for x in input().split()]
cnt = 0
for p in range(1, 2 ** M):
V = [[] for i in range(N)]
idx = 0
while p:
if p % 2:
V[E[idx][0]].append(E[idx][1])
V[E[idx][1]].append(E[idx][0])
idx += 1
p //= 2
if sum([len(v) for v in V]) == 2 * (N - 1) and len(V[0]) == 1:
P = [0] + V[0]
while len(V[P[-1]]) == 2:
P += [V[P[-1]][0] if V[P[-1]][0] != P[-2] else V[P[-1]][1]]
cnt += 1 if len(P) == N else 0
print(cnt) | N, M = list(map(int, input().split()))
G = [[] for i in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
G[a - 1].append(b - 1)
G[b - 1].append(a - 1)
def dfs(V, v):
_V = [v for v in V]
_V[v] = 1
cnt = 0
if sum(_V) == N:
return 1
else:
for adj in G[v]:
if _V[adj] == 0:
cnt += dfs(_V, adj)
return cnt
print((dfs([0] * N, 0))) | p03805 |
n,m=list(map(int, input().split()))
alist=[]
for i in range(m):
a,b=list(map(int, input().split()))
alist.append([a,b])
alist.append([b,a])
ans=0
import itertools
t=[i for i in range(1,n+1)]
blist=list(itertools.permutations(t,n))
ans=0
for i in blist:
flag=True
for j in range(n-1):
if [i[j],i[j+1]] not in alist:
flag=False
if i[0]!=1:
flag=False
if flag:
ans+=1
print(ans) | n,m=list(map(int, input().split()))
alist=[]
for i in range(m):
a,b=list(map(int, input().split()))
alist.append([a,b])
alist.append([b,a])
ans=0
import itertools
t=[i for i in range(1,n+1)]
blist=list(itertools.permutations(t,n))
ans=0
for i in blist:
flag=True
for j in range(n-1):
if [i[j],i[j+1]] not in alist:
flag=False
if i[0]!=1:
flag=False
if flag:
ans+=1
print(ans) | p03805 |
import sys
input = sys.stdin.readline
from operator import itemgetter
lis = []
n = 0
m = 0
ans = 0
def dfs(i, d, fr, used):
global lis, ans
if i in used:
return
if d == n - 1:
ans += 1
return
for j in lis[i]:
if j != fr:
used.append(i)
# print(i+1 , j+1)
dfs(j, d+1, i, used)
used.pop()
def main():
global lis, n, m, ans
n, m = list(map(int, input().strip().split()))
lis = [[] for _ in range(8)]
for _ in range(m):
a, b = list([x-1 for x in list(map(int, input().strip().split()))])
lis[a].append(b)
lis[b].append(a)
# print("##")
dfs(0, 0, -1, [])
print(ans)
if __name__ == '__main__':
main()
| import sys
input = sys.stdin.readline
from operator import itemgetter
lis = []
n = 0
m = 0
ans = 0
visited = []
def dfs(i, d, fr):
global lis, ans, visited
if visited[i] == 1:
return
if d == n - 1:
ans += 1
return
for j in lis[i]:
if j != fr:
visited[i] = 1
# print(i+1 , j+1)
dfs(j, d+1, i)
visited[i] = -1
def main():
global lis, n, m, ans, visited
n, m = list(map(int, input().strip().split()))
lis = [[] for _ in range(n)]
visited = [-1] * n
for _ in range(m):
a, b = list([x-1 for x in list(map(int, input().strip().split()))])
lis[a].append(b)
lis[b].append(a)
# print("##")
dfs(0, 0, -1)
print(ans)
if __name__ == '__main__':
main()
| p03805 |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
##############################
# N = 頂点の数(= 数字の数)
# M = 辺の数(= aの行数)
N, M = list(map(int, input().split()))
graph = [ [0 for _ in range(N)] for _ in range(N) ]
visited = [False] * N
for i in range(M):
a, b = list(map(int, input().split()))
graph[a-1][b-1] = 1
graph[b-1][a-1] = 1
#print(graph)
# u は 0-index
def dfs(u):
visited[u] = True
if False in visited:
pass
else:
return 1
count = 0
for i in range(N):
if graph[u][i] == False: continue
if visited[i]: continue
visited[i] = True
count += dfs(i)
visited[i] = False
return count
count = dfs(0)
print(count) |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
##############################
# https://atcoder.jp/contests/abc054/tasks/abc054_c
# N = 頂点の数(= 数字の数)
# M = 辺の数(= aの行数)
N, M = list(map(int, input().split()))
graph = [ [0 for _ in range(N)] for _ in range(N) ]
visited = [False] * N
for i in range(M):
a, b = list(map(int, input().split()))
graph[a-1][b-1] = 1
graph[b-1][a-1] = 1
#print(graph)
# u は 0-index
def dfs(u):
if False in visited:
pass
else:
return 1
count = 0
for i in range(N):
if graph[u][i] == False: continue
if visited[i]: continue
visited[i] = True
count += dfs(i)
visited[i] = False
return count
visited[0] = True
count = dfs(0)
print(count) | p03805 |
#制約が小さいので全探索する
n,m=list(map(int,input().split()))
#辺があるかどうかが知りたい→隣接行列表現
es=[[0]*n for i in range(n)]
for i in range(m):
a,b=list(map(int,input().split()))
es[a-1][b-1]=1
es[b-1][a-1]=1
#順列を作る
from itertools import permutations
per=[i+1 for i in range(n-1)]
per=list(permutations(per,n-1))
#全探索する
ans=0
for i in per:
cnt=0
if es[0][i[0]]==0:
continue
else:
for j in range(1,n-1):
if es[i[j]][i[j-1]]==0:
cnt+=1
if cnt==0:
ans=ans+1
print(ans)
| n,m=list(map(int,input().split()))
# 再帰の深さが1000を超えそうなときはこれをやっておく
import sys
sys.setrecursionlimit(10**7)
#隣接行列表現
es=[[0 for i in range(n)] for j in range(n)]
for i in range(m):
a,b=list(map(int,input().split()))
es[a-1][b-1]=1
es[b-1][a-1]=1
#深さ優先探索
def dfs(v,visited):
ans=0
#自分が今いるところは探索済にする
visited[v-1]=1
#全部探索できたことになる
if visited==check:
visited[v-1]=0
return 1
#vから行けるところを考える
for i in range(n):
#道があって未訪問
if visited[i]==0 and es[v-1][i]==1:
ans=ans+dfs(i+1,visited)
#次の探索のため未訪問にしておく
visited[v-1]=0
return ans
visited=[0 for i in range(n)]
check=[1 for i in range(n)]
print((dfs(1,visited)))
| p03805 |
N, M = list(map(int, input().split()))
E = [[] for _ in range(N)]
for m in range(M):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
E[a].append(b)
E[b].append(a)
check = [False] * N
check[0] = True
def dfs(v):
if sum(check) == N:
return 1
ans = 0
for u in E[v]:
if check[u]:
continue
check[u] = True
ans += dfs(u)
check[u] = False
return ans
print((dfs(0)))
| from itertools import permutations
N, M = list(map(int, input().split()))
E = [set() for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
E[a-1].add(b-1)
E[b-1].add(a-1)
ans = 0
for p in permutations([i for i in range(1, N)]):
i = 0
for j in p:
if j not in E[i]:
break
i = j
else:
ans += 1
print(ans) | p03805 |
from collections import deque
def dfs(G, visited, s, n, ans):
# すべての頂点を訪れた場合の処理
if all(visited) :
ans += 1
return ans
# 次の頂点の探索
for i in G[s] :
if visited[i] == False :
visited[i] = True
ans = dfs(G, visited, i, n, ans)
visited[i] = False
return ans
# グラフGの入力
n,m = list(map(int,input().split()))
G = [[] for j in range(n)]
for i in range(m) :
a,b = list(map(int,input().split()))
G[a-1].append(b-1)
G[b-1].append(a-1)
visited = [False for i in range(n)]
visited[0] = True
ans = 0
print((dfs(G, visited, 0, n, ans))) | # -*- coding: utf-8 -*-
n,m = list(map(int, input().split()))
graph = [[] for j in range(n)]
for i in range(m):
a,b = list(map(int, input().split()))
graph[a-1].append(b-1)
graph[b-1].append(a-1)
used = [False]*n
used[0] = True
def DFS(v,used):
if all(used):
return 1
ans = 0
for i in graph[v]:
if used[i]:
continue
used[i] = True
ans += DFS(i,used)
used[i] = False
return ans
print((DFS(0,used))) | p03805 |
N,M = list(map(int,input().split()))
P=[]
for m in range(M):
P.append(list(map(int,input().split())))
from itertools import combinations
ans=0
for c in combinations(list(range(M)),N-1):
visit = [1]
P_visit=[]
v=0
start=visit[0]
while v < 100:
v+=1
for c_ in c:
if c_ in P_visit:
continue
if P[c_][0] == start:
visit.append(P[c_][1])
start = P[c_][1]
P_visit.append(c_)
elif P[c_][1] == start:
visit.append(P[c_][0])
start = P[c_][0]
P_visit.append(c_)
if len(set(visit))== N:
ans += 1
print(ans) | from itertools import permutations
N,M = list(map(int,input().split()))
P=[]
for m in range(M):
P.append(list(map(int,input().split())))
ad={}
for _ in range(1,N+1):
ad[_]=set()
for p in P:
ad[p[0]].add(p[1])
ad[p[1]].add(p[0])
ans=0
for p in permutations(list(range(2,N+1)),N-1):
ans_flag=True
start=1
for p_ in p:
end=p_
# print(start,end ,end in ad[start])
if end not in ad[start]:
# print('break')
ans_flag=False
break
start=p_
if ans_flag==True:
ans+=1
print(ans) | p03805 |
from collections import defaultdict
from itertools import permutations
N, M = list(map(int, input().split()))
dic = defaultdict(list)
for i in range(M):
a, b = list(map(int, input().split()))
dic[a-1] += [b-1]
dic[b-1] += [a-1]
ans = 0
ls = permutations(list(range(1,N)))
for l in ls:
l = [0]+list(l)
for i in range(N-1):
if not l[i+1] in dic[l[i]]:
break
if i==N-2:
ans += 1
print(ans) | from itertools import permutations
N, M, *L = list(map(int, open(0).read().split()))
dic = [[] for i in range(N+1)]
for a, b in zip(*[iter(L)]*2):
dic[a].append(b)
dic[b].append(a)
ans = 0
for l in permutations(list(range(2,N+1))):
l = [1]+list(l)
for i in range(N-1):
if l[i+1] not in dic[l[i]]:
break
else:
ans += 1
print(ans) | p03805 |
import sys
from itertools import permutations
input = sys.stdin.readline
def main():
N, M = list(map(int, input().split()))
link = [[False] * N for i in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
link[a-1][b-1] = True
link[b-1][a-1] = True
ans = 0
path = [i for i in range(1, N)]
for p in permutations(path):
if link[0][p[0]]:
ok = True
for i in range(N-2):
if not link[p[i]][p[i+1]]:
ok = False
break
if ok:
ans += 1
print(ans)
if __name__ == "__main__":
main() | from itertools import permutations
import sys
input = sys.stdin.readline
def main():
N, M = list(map(int, input().split()))
link = [[False] * N for i in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
link[a-1][b-1] = True
link[b-1][a-1] = True
ans = 0
for p in permutations(list(range(1, N))):
# print(0, p)
pre = 0
ok = True
for t in p:
if not link[pre][t]:
ok = False
break
pre = t
if ok:
ans += 1
print(ans)
if __name__ == "__main__":
main() | p03805 |
N, M = [int(v) for v in input().split()]
tbl = [[0] * (N + 1) for _ in range(N+1)]
for _ in range(M):
a, b = [int(v) for v in input().split()]
tbl[a][b] = 1
tbl[b][a] = 1
ans = 0
paths = [[1, ]]
while paths:
p = paths.pop()
for i in range(1, N + 1):
if p[-1] == i: continue
if tbl[p[-1]][i] and i not in p:
np = p + [i]
if len(np) == N:
ans += 1
paths.append(np)
print(ans) | N, M = [int(v) for v in input().split()]
tbl = [[0] * (N + 1) for _ in range(N + 1)]
def dfs(v, visited):
if len(visited) == N:
return 1
ans = 0
for i in range(1, N + 1):
if i == v: continue
if tbl[i][v] == 1 and i not in visited:
visited.append(i)
ans += dfs(i, visited)
visited.pop()
return ans
for _ in range(M):
a, b = [int(v) for v in input().split()]
tbl[a][b] = 1
tbl[b][a] = 1
paths = [1, ]
print((dfs(1, paths))) | p03805 |
import sys
input_int = lambda:int(eval(input()))
input_ints = lambda:list(map(int,input().split()))
input_ints_list = lambda:list(input_ints())
input_str = lambda:eval(input())
input_strs = lambda:input().split()
input_lines = lambda n,f:[f() for _ in range(n)]
import functools,fractions
gcd = lambda a:functools.reduce(fractions.gcd,a) # 最大公約数(リスト)
lcm_base = lambda a,b:(a*b)//fractions.gcd(a,b) # 最小公倍数(2値)
lcm = lambda a:functools.reduce(lcm_base,a,1) # 最小公倍数(リスト)
import itertools
permutations = lambda a,n:itertools.permutations(a,n) # 順列
combinations = lambda a,n:itertools.combinations(a,n) # 組み合わせ
product = lambda a,b:itertools.product(a,b) # 二つのリストの直積
init_array_1dim = lambda v,n:[v for _ in range(n)]
init_array_2dim = lambda v,n,m:[[v for _ in range(n)] for _ in range(m)]
import math
# 四捨五入はround
ceil = lambda a:math.ceil(a) # 切り上げ
floor = lambda a:math.floor(a) # 切り捨て
def dfs(v,n,graph,visited):
if all(visited):return 1
ans = 0
for i in range(n):
if graph[v][i] == False:continue
if visited[i]:continue
visited[i] = True
ans += dfs(i,n,graph,visited)
visited[i] = False
return ans
def init_graph(n,a,directed=False):
visited = init_array_1dim(False,n)
graph = init_array_2dim(False,n,n)
for e in a:
graph[e[0]-1][e[1]-1] = True
if not directed:graph[e[1]-1][e[0]-1] = True # 無向グラフの場合
return visited,graph
def solution():
N,M = input_ints()
ab = input_lines(M,input_ints_list)
visited,graph = init_graph(N,ab)
visited[0] = True
print((dfs(0,N,graph,visited)))
if __name__ == '__main__':
solution() | import sys
input_int = lambda:int(eval(input()))
input_ints = lambda:list(map(int,input().split()))
input_ints_list = lambda:list(input_ints())
input_str = lambda:eval(input())
input_strs = lambda:input().split()
input_lines = lambda n,f:[f() for _ in range(n)]
import functools,fractions
gcd = lambda a:functools.reduce(fractions.gcd,a) # 最大公約数(リスト)
lcm_base = lambda a,b:(a*b)//fractions.gcd(a,b) # 最小公倍数(2値)
lcm = lambda a:functools.reduce(lcm_base,a,1) # 最小公倍数(リスト)
import itertools
permutations = lambda a,n:itertools.permutations(a,n) # 順列
combinations = lambda a,n:itertools.combinations(a,n) # 組み合わせ
product = lambda a,b:itertools.product(a,b) # 二つのリストの直積
init_array_1dim = lambda v,n:[v for _ in range(n)]
init_array_2dim = lambda v,n,m:[[v for _ in range(n)] for _ in range(m)]
import math
# 四捨五入はround
ceil = lambda a:math.ceil(a) # 切り上げ
floor = lambda a:math.floor(a) # 切り捨て
def dfs_graph(v,n,graph,visited):
if all(visited):return 1
ans = 0
for i in range(n):
if graph[v][i] == False:continue
if visited[i]:continue
visited[i] = True
ans += dfs_graph(i,n,graph,visited)
visited[i] = False
return ans
def init_graph(n,a,directed=False):
visited = init_array_1dim(False,n)
graph = init_array_2dim(False,n,n)
for e in a:
graph[e[0]-1][e[1]-1] = True
if not directed:graph[e[1]-1][e[0]-1] = True # 無向グラフの場合
return visited,graph
def solution():
N,M = input_ints()
ab = input_lines(M,input_ints_list)
visited,graph = init_graph(N,ab)
visited[0] = True
print((dfs_graph(0,N,graph,visited)))
if __name__ == '__main__':
solution() | p03805 |
#!/usr/bin/python
# -*- Coding: utf-8 -*-
n,m = list(map(int,input().split()))
H = [[0 for _ in range(n)] for _ in range(n) ]
edge_list = []
for _ in range(m):
a, b = list(map(int,input().split()))
edge_list.append([a-1,b-1])
H[a-1][b-1] = 1
H[b-1][a-1] = 1
l = [0 for _ in range(n)]
ans = 0
l[0] = 1
def dfs(node,x):
global ans
if x.count(0) == 0:
ans += 1
return 0
else:
visited = x
visited[node] = 1
for node_,edge_ in enumerate(H[node]):
if edge_ == 1 and visited[node_] != 1:
visited[node_] = 1
visited[node] = 1
dfs(node_,visited)
visited[node_] = 0
#頂点iをここで未訪問にすることが一番重要!!!!!
dfs(0,l)
print(ans)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
n,m = list(map(int,input().split()))
H = [[0 for _ in range(n)] for _ in range(n) ]
for _ in range(m):
a, b = list(map(int,input().split()))
H[a-1][b-1] = 1
H[b-1][a-1] = 1
l = [0 for _ in range(n)]
ans = 0
def dfs(node,visited):
global ans
if visited.count(0) == 0:
ans += 1
return 0
else:
visited[node] = 1
for node_,edge_ in enumerate(H[node]):
if edge_ == 1 and visited[node_] != 1:
visited[node_] = 1
visited[node] = 1
dfs(node_,visited)
visited[node_] = 0
dfs(0,l)
print(ans) | p03805 |
def abc054_c_one_stroke_paths():
import copy
N, M = list(map(int, input().split()))
# create graph G
G = {}
for m in range(M):
a, z = list(map(int, input().split()))
G[a] = G.get(a, [])
G[a].append(z)
G[z] = G.get(z, [])
G[z].append(a)
# print(G)
# find all paths
if G.get(1, 0) == 0:
print((0))
return
paths = []
def solve(a, path):
path.append(a)
if len(path) == N:
paths.append(path)
return
for z in G.get(a):
p = copy.copy(path)
if z in p:
continue
solve(z, p)
solve(1, [])
# print(paths)
print((len(paths)))
##########
if __name__ == "__main__":
abc054_c_one_stroke_paths()
| def abc054_c_one_stroke_paths():
N, M = list(map(int, input().split()))
# create graph G
G = {}
for m in range(M):
a, z = list(map(int, input().split()))
G[a] = G.get(a, [])
G[a].append(z)
G[z] = G.get(z, [])
G[z].append(a)
# print(G)
# find all paths
if G.get(1, 0) == 0:
print((0))
return
def dfs(a, path):
path.append(a)
if len(path) == N:
return 1
paths = 0
for z in G.get(a):
if z in path:
continue
paths += dfs(z, path[:])
return paths
print((dfs(1, [])))
##########
if __name__ == "__main__":
abc054_c_one_stroke_paths()
| p03805 |
N,M=list(map(int,input().split()))
inp=[list(map(int,input().split())) for _ in range(M)]
g=[[] for _ in range(N)]
[g[a-1].append(b-1) for a,b in inp]
[g[b-1].append(a-1) for a,b in inp]
from itertools import permutations
seq=[i for i in range(N)]
test=list(permutations(seq))
cnt=0
for t in test:
if t[0]==0:
for i in range(N-1):
if t[i+1] not in g[t[i]]:
break
else:
cnt+=1
print(cnt) | n,m=list(map(int,input().split()))
ab=[list(map(int,input().split())) for _ in [0]*m]
g=[[] for _ in [0]*n]
[g[a-1].append(b-1) for a,b in ab]
[g[b-1].append(a-1) for a,b in ab]
from itertools import permutations
cnt=0
for i in permutations(list(range(1,n))):
i=(0,)+i
for j in range(n-1):
if i[j+1] not in g[i[j]]:
break
else:
cnt+=1
print(cnt) | p03805 |
import itertools
N, M = list(map(int, input().split()))
ab = []
for i in range(M):
ab.append(list(map(int, input().split())))
ans = 0
if M >= N - 1:
for i in list(itertools.combinations(ab, N - 1)):
g = {}
for j in range(N):
g[j + 1] = []
for j, k in i:
g[j].append(k)
g[k].append(j)
if len(g[1]) == 1:
p = 1
q = g[p][0]
for j in range(N - 2):
l = g[q]
if len(l) != 2:
break
l.remove(p)
p = q
q = l[0]
else:
ans += 1
print(ans) | import itertools
N, M = list(map(int, input().split()))
e = set([])
for i in range(M):
a, b = list(map(int, input().split()))
e.add((a, b))
ans = 0
for i in list(itertools.permutations(list(range(2, N + 1)))):
a = 1
for b in i:
if (a, b) in e or (b, a) in e:
a = b
continue
break
else:
ans += 1
print(ans)
| p03805 |
def na(): return list(map(int, input().split()))
n, m = na()
edges = [[False for _ in range(n)] for _ in range(n)]
for i in range(m):
a, b = na()
a -= 1
b -= 1
edges[a][b] = True
edges[b][a] = True
pathes = {'0'}#permutationで求めたpath
for i in range(n-1):
buf = set()
for pre_path in pathes:
for v in map(str, list(range(1, n))):
if not(v in pre_path):
buf.add(pre_path + v)
pathes = buf.copy()
##print(pathes)
##print(edges)
ans = 0
for path in pathes:
flg = True
for i in range(1, n):
a, b = list(map(int, [path[i-1], path[i]]))
## print(a, b, edges[a][b])
if not edges[a][b]:
flg = False
break
if flg:
ans += 1
print(ans) | def ary(r, c, v): return [[v for _ in range(c)] for _ in range(r)]
n, m = list(map(int, input().split()))
e = ary(n, n, False)
for i in range(m):
a, b = list(map(int, input().split()))
#頂点を0-indexedに変換
a -= 1
b -= 1
e[a][b] = True
e[b][a] = True
ps = set()
ps.add('0')
for cnt in range(1, n):
t = set()
for p in ps:
for i in map(str, list(range(1, n))):
if not(i in p):
t.add(p + i)
ps = t.copy()
ans = 0
for p in ps:
flg = True
for i in range(n - 1):
a = int(p[i])
b = int(p[i + 1])
if not e[a][b]:
flg = False
break
if flg:
ans += 1
print(ans) | p03805 |
def ary(r, c, v): return [[v for _ in range(c)] for _ in range(r)]
n, m = list(map(int, input().split()))
e = ary(n, n, False)
for i in range(m):
a, b = list(map(int, input().split()))
#頂点を0-indexedに変換
a -= 1
b -= 1
e[a][b] = True
e[b][a] = True
ps = set()
ps.add('0')
for cnt in range(1, n):
t = set()
for p in ps:
for i in map(str, list(range(1, n))):
if not(i in p):
t.add(p + i)
ps = t.copy()
ans = 0
for p in ps:
flg = True
for i in range(n - 1):
a = int(p[i])
b = int(p[i + 1])
if not e[a][b]:
flg = False
break
if flg:
ans += 1
print(ans) | def main():
import sys
sys.setrecursionlimit(10 ** 7)
N, M = list(map(int, input().split()))
g = tuple(set() for _ in range(N))
for _ in range(M):
a, b = (int(x) - 1 for x in input().split())
g[a].add(b)
g[b].add(a)
def dfs(v=0, visited=1 << 0):
if visited == (1 << N) - 1:
return 1
ret = 0
for u in g[v]:
if (visited >> u) & 1:
continue
ret += dfs(u, visited | (1 << u))
return ret
ans = dfs()
print(ans)
if __name__ == '__main__':
main()
# import sys
#
# sys.setrecursionlimit(10 ** 7)
#
# input = sys.stdin.readline
# rstrip()
# int(input())
# map(int, input().split())
| p03805 |
n,m=list(map(int,input().split()))
a=[]
for i in range(m):
ai,bi=list(map(int,input().split()))
a.append([ai,bi])
ni=[0]*n
nii=[]
def pathm(n,a,bi,pcnt,ni):
if n==1:
pcnt=pcnt+1
# print("2:","n:",n,"bi:",bi,"pcnt:",pcnt)
return pcnt
else:
n=n-1
nii.append(bi)
for mm in range(m):
if a[mm][0]==bi and not a[mm][1] in nii:
# if a[mm][0]==bi :
ni[a[mm][1]-1]=1
# print("1:","n:",n,"mm:",mm,"a[mm][1]:",a[mm][1],"pcnt:",pcnt)
pcnt=pathm(n,a,a[mm][1],pcnt,ni)
if a[mm][1]==bi and not a[mm][0] in nii:
# if a[mm][1]==bi and ni[a[mm][0]-1]==0 :
ni[a[mm][0]-1]=1
# ni[mm]=1
# print("1:","n:",n,"mm:",mm,"a[mm][0]:",a[mm][0],"pcnt:",pcnt)
pcnt=pathm(n,a,a[mm][0],pcnt,ni)
nii.pop()
return pcnt
pcnt=0
pcnt1=pathm(n,a,1,pcnt,ni)
print(pcnt1)
| q=[]
qq=[]
def dfs(j,q,icnt,count,n,qq):
if len(qq)==n:
count+=1
# print("1",n,j,icnt,count,q[j],qq)
return count
icnt+=1
for j2 in q[j]:
if not j2 in qq:
qq.append(j2)
# print("2",n,j,icnt,count,q[j],qq)
count=dfs(j2,q,icnt,count,n,qq)
qq.pop()
# print("3",n,j,icnt,count,q[j],qq)
return count
n,m=list(map(int,input().split()))
ab=[[0]*2 for i in range(m)]
for i in range(m):
ab[i]=list(map(int,input().split()))
#n=3
#m=3
#ab=[[1,2],[1,3],[2,3]]
#n=7
#m=7
#ab=[[1,3],[2,7],[3,4],[4,5],[4,6],[5,6],[6,7]]
q=[[]*2 for i in range(n)]
for i in range(m):
if not q[ab[i][1]-1] in q[ab[i][0]-1]:
q[ab[i][0]-1].append(ab[i][1]-1)
if not q[ab[i][0]-1] in q[ab[i][1]-1]:
q[ab[i][1]-1].append(ab[i][0]-1)
#print(q)
count=0
j=0
qq=[j]
icnt=1
count=dfs(j,q,icnt,count,n,qq)
print(count) | p03805 |
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
h = logging.FileHandler("logtest.log")
logger.addHandler(h)
N, M = list(map(int, input().split()))
open_list = [[] for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
open_list[a].append(b)
open_list[b].append(a)
logger.info("open_list: {}\n".format(open_list))
# 探索済みリスト
closed_list = [False] * N
closed_list[0] = True
cnt = 0
level = 1
# 深さ優先探索
def dfs(target):
global cnt, level
logger.info("***********open_list[target]: {}".format(open_list[target]))
if all(closed_list):
cnt += 1
logger.info("[level: {}] closed_list: {}".format(level, closed_list))
logger.info("cnt: {}".format(cnt))
logger.info("*****************************************")
return
# open_listリストのnode
for node in open_list[target]:
logger.info("node: {}".format(node))
logger.info("[level: {}] closed_list: {}".format(level, closed_list))
# 探索済みでない場合
if closed_list[node] is False:
# 探索開始
closed_list[node] = True
# 再帰
level += 1
dfs(node)
level = 1
# levalを戻す
closed_list[node] = False
logger.info("[level: {}] closed_list: {}".format(level, closed_list))
return
dfs(0)
print(cnt)
| N, M = list(map(int, input().split()))
open_list = [[] for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
open_list[a].append(b)
open_list[b].append(a)
# 探索済みリスト
closed_list = [False] * N
closed_list[0] = True
cnt = 0
level = 1
# 深さ優先探索
def dfs(target):
global cnt, level
if all(closed_list):
cnt += 1
return
# open_listリストのnode
for node in open_list[target]:
# 探索済みでない場合
if closed_list[node] is False:
# 探索開始
closed_list[node] = True
# 再帰
level += 1
dfs(node)
level = 1
# levalを戻す
closed_list[node] = False
return
dfs(0)
print(cnt)
| p03805 |
# -*- coding: utf-8 -*-
# DFSでやる版
N, M = list(map(int, input().split()))
# 入力値の頂点ペア(辺)を格納する配列
a = [0] * M
b = [0] * M
# 頂点ペアが隣接しているかどうかを格納する配列
graph = [[False for i in range(N)] for j in range(N)]
# 入力値の頂点ペア(辺)を格納していくループ
for i in range(M):
a[i], b[i] = list(map(int, input().split()))
# 添字に合わせて入力値から1減らしておく
a[i] -= 1
b[i] -= 1
# 入力値の内容に合わせて、隣接していることを記録
graph[a[i]][b[i]] = True
graph[b[i]][a[i]] = True
cnt = 0
p = [0] * N
def dfs(pos, mask):
# 関数内で更新して外部で参照する変数のglobal宣言
global cnt
# 最後まで到達できた時はここを通る
if pos == N:
# 前提としてスタート地点(添字0)が0かどうか確認
if p[0] == 0:
for i in range(N-1):
# 各辺が存在(各頂点ペアが隣接)しているか確認していく
if graph[p[i]][p[i+1]] == False:
break
# 全て存在すれば条件を満たすのでカウント+1
if i == N-2:
cnt += 1
return
for i in range(N):
# 残っている数の中にiがまだ残っている場合
# (maskの中に(1<<i)のビットがまだ残っていればTrueを返す)
if mask & (1<<i):
p[pos] = i
# 残っている数からiを取り除く
# (排他的論理和XORで重複部分が0になる)
dfs(pos+1, mask^(1<<i))
# 0からN-1までの数の集合
dfs(0, (1<<N)-1)
print(cnt)
# 参考:2進数の1を左へ3ビット移動(1→8)
# (1 << 3) | # -*- coding: utf-8 -*-
import sys
from itertools import permutations
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(eval(input()))
def MAP(): return list(map(int, input().split()))
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7
N, M = MAP()
edges = set()
for i in range(M):
a, b = MAP()
a -= 1; b -= 1
edges.add((a, b))
edges.add((b, a))
cnt = 0
for perm in permutations(list(range(N))):
if perm[0] != 0:
continue
for i in range(N-1):
a = perm[i]
b = perm[i+1]
if (a, b) not in edges:
break
else:
cnt += 1
print(cnt)
| p03805 |
# -*- coding: utf-8 -*-
import sys
from itertools import permutations
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(eval(input()))
def MAP(): return list(map(int, input().split()))
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7
N, M = MAP()
edges = set()
for i in range(M):
a, b = MAP()
a -= 1; b -= 1
edges.add((a, b))
edges.add((b, a))
cnt = 0
for perm in permutations(list(range(N))):
if perm[0] != 0:
continue
for i in range(N-1):
a = perm[i]
b = perm[i+1]
if (a, b) not in edges:
break
else:
cnt += 1
print(cnt)
| # -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(eval(input()))
def MAP(): return list(map(int, input().split()))
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7
N, M = MAP()
G = list2d(N, N, 0)
for i in range(M):
a, b = MAP()
a -= 1; b -= 1
G[a][b] = G[b][a] = 1
# dp[S][i] := 訪問済の頂点集合をSとして、最後に頂点iにいる場合の通り数
dp = list2d(1<<N, N, 0)
# 最初は頂点1にいる状態から
dp[1][0] = 1
for S in range(1, 1<<N):
for i in range(N):
# iが遷移元に含まれていない
if not S & 1<<i:
continue
for j in range(N):
# jが遷移元に含まれている(ので遷移先にはできない)
if S & 1<<j:
continue
# 辺の張られた頂点間であれば遷移させる
if G[i][j]:
dp[S|1<<j][j] += dp[S][i]
# 全頂点訪問できた通り数を合計する
ans = sum(dp[(1<<N)-1])
print(ans)
| p03805 |
#DFS
from collections import deque
N, M = list(map(int, input().split()))
G = [[] for _ in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
G[a-1].append(b-1)
G[b-1].append(a-1)
stack = deque([(0, 0)])
visited = [0] * N
depth = 0
ans = 0
while stack:
now, depth = stack.pop()
if depth == N-1:
ans += 1
continue
visited[depth] = now
for nxt in G[now]:
if nxt not in visited[:depth+1]:
stack.append((nxt, depth+1))
print(ans) | #順列全探索
from itertools import permutations
N, M = list(map(int, input().split()))
G = [[0]*N for _ in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
G[a-1][b-1] = 1
G[b-1][a-1] = 1
perms = permutations(list(range(1, N)))
ans = 0
for perm in perms:
now = 0
for v in perm:
if G[now][v] == 0:
break
now = v
else:
ans += 1
print(ans) | p03805 |
from collections import defaultdict
from itertools import permutations
def main():
N, M = list(map(int, input().split()))
g = defaultdict(list)
for _ in range(M):
a, b = list(map(int, input().split()))
g[a].append(b)
g[b].append(a)
ans = 0
for route in permutations(list(range(2, N + 1)), N - 1):
ok = True
now = 1
for r in route:
if r in g[now]:
now = r
else:
ok = False
if ok:
ans += 1
print(ans)
if __name__ == '__main__':
main()
| from collections import defaultdict
from itertools import permutations
def main():
N, M = list(map(int, input().split()))
graph = defaultdict(list)
for _ in range(M):
a, b = list(map(int, input().split()))
graph[a].append(b)
graph[b].append(a)
ans = 0
for route in permutations(list(range(2, N + 1)), N - 1):
ok = True
now = 1
for node in route:
if node in graph[now]:
now = node
else:
ok = False
ans += ok
print(ans)
if __name__ == '__main__':
main()
| p03805 |
from collections import defaultdict
from itertools import permutations
def main():
N, M = list(map(int, input().split()))
graph = defaultdict(list)
for _ in range(M):
a, b = list(map(int, input().split()))
graph[a].append(b)
graph[b].append(a)
ans = 0
for route in permutations(list(range(2, N + 1)), N - 1):
ok = True
now = 1
for node in route:
if node in graph[now]:
now = node
else:
ok = False
ans += ok
print(ans)
if __name__ == '__main__':
main()
| from collections import defaultdict
from itertools import permutations
def main():
N, M = list(map(int, input().split()))
s = set()
for _ in range(M):
a, b = list(map(int, input().split()))
s.add((a, b))
s.add((b, a))
ans = 0
for x in permutations(list(range(2, N + 1))):
now = 1
for i in range(len(x)):
if (now, x[i]) not in s:
break
now = x[i]
else:
ans += 1
print(ans)
if __name__ == '__main__':
main()
| p03805 |
import itertools
n,m=list(map(int,input().split()))
edge=[[]for i in range(n+1)]
for i in range(m):
a,b=list(map(int,input().split()))
edge[a].append(b)
edge[b].append(a)
ans=0
for i in itertools.permutations(list(range(1,n+1))):
if i[0]!=1:
continue
for j in range(n-1):
if i[j+1] not in edge[i[j]]:
break
else:
ans+=1
print(ans) | from itertools import permutations
n,m=list(map(int,input().split()))
graph=[[] for i in range(n+1)]
for i in range(m):
a,b=list(map(int,input().split()))
graph[a].append(b)
graph[b].append(a)
ans=0
for i in permutations(list(range(1,n+1))):
if i[0]!=1:
continue
for j in range(n-1):
if i[j+1] not in graph[i[j]]:
break
else:
ans+=1
print(ans) | p03805 |
import itertools
N, M = list(map(int, input().split()))
edges = {tuple(sorted(map(int, input().split()))) for _ in range(M)}
answer = 0
for pattern in itertools.permutations(list(range(2, N+1)), N-1):
l = [1] + list(pattern)
answer += sum(1 for edge in zip(l, l[1:]) if tuple(sorted(edge)) in edges)==N-1
print(answer) | import itertools
N, M = list(map(int, input().split()))
edges = {tuple(sorted(map(int, input().split()))) for _ in range(M)}
answer = 0
for i in itertools.permutations(list(range(2, N+1)), N-1):
l = [1] + list(i)
answer += sum(1 for edge in zip(l, l[1:]) if tuple(sorted(edge)) in edges) == N-1
print(answer) | p03805 |
import itertools
N, M = list(map(int, input().split()))
edges = [tuple(sorted(map(int, input().split()))) for _ in range(M)]
answer = 0
for i in itertools.permutations(list(range(2, N+1)), N-1):
l = [1] + list(i)
answer += sum(1 for x in zip(l, l[1:]) if tuple(sorted(x)) in edges) == N-1
print(answer) | from itertools import permutations
N, M = list(map(int, input().split()))
AB = set([tuple(sorted(map(int, input().split()))) for _ in range(M)])
answer = 0
for pattern in permutations(list(range(2, N+1)), N-1):
pattern = [1] + list(pattern)
for i in zip(pattern[:-1], pattern[1:]):
if tuple(sorted(i)) not in AB:
break
else:
answer += 1
print(answer) | p03805 |
import itertools
n, m = list(map(int, input().split()))
h = [[0]*n for _ in range(n)]
for i in range(m):
a, b = list(map(int, input().split()))
h[a-1][b-1] = 1
h[b-1][a-1] = 1
ans = 0
x = list(itertools.permutations(list(range(1, n+1))))
for i in range(len(x)):
if x[i][0] == 1:
for j in range(n-1):
if h[x[i][j]-1][x[i][j+1]-1] == 0:
break
else:
ans += 1
print(ans) | import itertools
n, m = list(map(int, input().split()))
g = [[0]*n for _ in range(n)]
for _ in range(m):
a, b = list(map(int, input().split()))
a, b = a-1, b-1
g[a][b] = 1
g[b][a] = 1
a = list(itertools.permutations(list(range(n))))
ans = 0
for i in a:
if i[0] != 0:
break
for j in range(n-1):
if g[i[j]][i[j+1]] == 0:
break
else:
ans += 1
print(ans) | p03805 |
import sys
from itertools import permutations
def solve():
input = sys.stdin.readline
N, M = list(map(int, input().split()))
Edge = [[] for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
Edge[a-1].append(b-1)
Edge[b-1].append(a-1)
count = 0
for s in permutations(list(range(N)), N):
Visited = [False for _ in range(N)]
for i, n in enumerate(s):
if i == 0:
if n != 0: break
else: Visited[0] = True
else:
if n in Edge[s[i-1]]: Visited[n] = True
else: break
else: count += 1
print(count)
return 0
if __name__ == "__main__":
solve() | import sys
from itertools import permutations
def solve():
N, M = list(map(int, input().split()))
Edge = [[] for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
Edge[a-1].append(b-1)
Edge[b-1].append(a-1)
count = 0
for order in permutations(list(range(N))):
if order[0] != 0: continue
for i in range(N-1):
if order[i+1] not in Edge[order[i]]: break
else: count += 1
print(count)
return 0
if __name__ == "__main__":
solve() | p03805 |
# -*- coding: utf-8 -*-
line = input().split(" ")
n = int(line[0])
m = int(line[1])
edge = [[] for _ in range(n+1)]
for _ in range(m):
line = input().split(" ")
a = int(line[0])
b = int(line[1])
edge[a].append(b)
edge[b].append(a)
visited = [False for _ in range(n+1)]
visited[0] = True#dummy
visited[1] = True
def solve(x):
allVisited = True
for e in visited:
allVisited = allVisited and e
if allVisited:
return 1
ret = 0
for e in edge[x]:
if not visited[e]:
visited[e] = True
ret += solve(e)
visited[e] = False
return ret
print((solve(1)))
| # -*- coding: utf-8 -*-
n,m = list(map(int, input().split()))
edge = [[] for _ in range(n+1)]
for _ in range(m):
a,b = list(map(int, input().split()))
a -= 1
b -= 1
edge[a].append(b)
edge[b].append(a)
visited = [False for _ in range(n)]
def dfs(v):
if all(visited):
return 1
res = 0
for e in edge[v]:
if not visited[e]:
visited[e] = True
res += dfs(e)
visited[e] = False
return res
visited[0] = True
print((dfs(0)))
| p03805 |
n,m=list(map(int,input().split()))
e=[[]for _ in[0]*-~n]
for _ in[0]*m:
a,b=list(map(int,input().split()))
e[a]+=[b]
e[b]+=[a]
candy=[[1]]
for _ in[0]*~-n:
tmp=[]
for c in candy:
for next in e[c[-1]]:
tmp+=[c+[next]]
candy=tmp
print((sum(c==set(range(1,n+1))for c in map(set,candy)))) | from itertools import permutations
N, M = list(map(int, input().split()))
edges = set()
for _ in range(M):
a, b = list(map(int, input().split()))
edges.add((a, b))
edges.add((b, a))
cnt = 0
for p in permutations(list(range(2, N + 1))):
cnt += all(move in edges for move in zip((1,) + p, p))
print(cnt) | p03805 |
# 入力
import sys
stdin = sys.stdin
def li(): return [int(x) for x in stdin.readline().split()]
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return [float(x) for x in stdin.readline().split()]
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(ns())
def nf(): return float(ns())
from itertools import permutations
# 全探索をするのです
n,m = li()
edges = set()
for _ in range(m):
a,b = li()
edges.add((a,b))
edges.add((b,a))
paths = permutations([str(i) for i in range(2,n+1)],n-1)
cnt = 0
for path in paths:
path = [1] + [int(i) for i in path]
exist = True
for i in range(n-1):
if not (path[i], path[i+1]) in edges:
exist = False
if exist:
cnt += 1
print(cnt) | import sys
stdin = sys.stdin
sys.setrecursionlimit(10**5)
def li(): return list(map(int, stdin.readline().split()))
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return list(map(float, stdin.readline().split()))
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())
from itertools import permutations
n,m = li()
graph = [[False]*n for _ in range(n)]
for _ in range(m):
a,b = li_()
graph[a][b] = True
graph[b][a] = True
cands = list(permutations([i for i in range(1,n)]))
ans = 0
for c in cands:
cand = [0] + list(c)
ok = True
for i in range(n-1):
if not graph[cand[i+1]][cand[i]]:
ok = False
if ok:
ans += 1
print(ans) | p03805 |
N,M = list(map(int,input().split()))
G = {}
for _ in range(M):
a,b = list(map(int,input().split()))
if a not in G:
G[a] = []
G[a].append(b)
if b not in G:
G[b] = []
G[b].append(a)
hist = [0 for _ in range(N+1)]
stack = [1]
hist[1] = 1
cnt = 0
F = {}
while stack:
cur = stack[-1]
if cur not in F:
F[cur] = G[cur][:]
F[cur] = iter(F[cur])
F1 = list(F[cur])
# print("cur={},F1={}".format(cur,F1))
if len(F1)>0:
F[cur] = iter(F1)
x = next(F[cur])
if hist[x]==0:
stack.append(x)
hist[x] = 1
else:
if sum(hist)==N:
cnt += 1
hist[cur]=0
del F[cur]
stack.pop()
else:
# print("cur={}".format(cur))
# print("stack={}".format(stack))
if sum(hist)==N:
cnt += 1
hist[cur]=0
del F[cur]
stack.pop()
print(cnt) | from itertools import permutations
def check(i,j):
if j==N-2 and x[j] in G[i]:
return True
if x[j] in G[i]:
return check(x[j],j+1)
return False
N,M = list(map(int,input().split()))
G = {i:[] for i in range(1,N+1)}
for _ in range(M):
a,b = list(map(int,input().split()))
G[a].append(b)
G[b].append(a)
cnt = 0
for x in permutations(list(range(2,N+1)),N-1):
if check(1,0):
cnt += 1
print(cnt) | p03805 |
import math
from math import gcd,pi,sqrt
INF = float("inf")
MOD = 10**9 + 7
import sys
sys.setrecursionlimit(10**6)
import itertools
import bisect
from collections import Counter,deque
def i_input(): return int(eval(input()))
def i_map(): return list(map(int, input().split()))
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return eval(input())
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def main():
N,m = i_map()
l = [[0]*N for i in range(N)]
for i in range(m):
a,b = i_map()
a -= 1
b -= 1
l[a][b] = 1
l[b][a] = 1
L = []
def dfs(n,a):
a = a + str(n)
if len(a) == N:
L.append(1)
return
for i in range(N):
if l[n][i] == 1 and str(i) not in a:
dfs(i,a)
dfs(0,"")
print((len(L)))
if __name__=="__main__":
main()
| import math
from math import gcd,pi,sqrt
INF = float("inf")
MOD = 10**9 + 7
import sys
sys.setrecursionlimit(10**6)
import itertools
import bisect
from collections import Counter,deque
def i_input(): return int(eval(input()))
def i_map(): return list(map(int, input().split()))
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return eval(input())
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def main():
global L
N,m = i_map()
l = [[0]*N for i in range(N)]
for i in range(m):
a,b = i_map()
a -= 1
b -= 1
l[a][b] = 1
l[b][a] = 1
L = 0
v = [0] * N
v[0] = 1
def dfs(n):
global L
if 0 not in v:
L += 1
return
for i in range(N):
if l[n][i] == 1 and v[i] == 0:
v[i] = 1
dfs(i)
v[i] = 0
dfs(0)
print(L)
if __name__=="__main__":
main()
| p03805 |
from collections import defaultdict
import itertools
n, m = list(map(int, input().split()))
connected_dict = defaultdict(lambda: [])
for i in range(m):
a, b = list(map(int, input().split()))
connected_dict[a].append(b)
connected_dict[b].append(a)
count = 0
for permutation in list(itertools.permutations(list(range(2, n + 1)))):
flag = True
pre_num = 1
for num in permutation:
if num not in connected_dict[pre_num]:
flag = False
break
pre_num = num
if flag:
count += 1
print(count)
| # One-stroke Path
import itertools
n, m = list(map(int, input().split()))
ab = {}
for i in range(n+1):
ab[i] = []
for i in range(m):
a, b = list(map(int, input().split()))
ab[a].append(b)
ab[b].append(a)
count = 0
for values in list(itertools.permutations(list(range(2, n+1)))):
pre = 1
for i, v in enumerate(values):
if(v not in ab[pre]):
break
if i == n-2:
count += 1
pre = v
print(count) | p03805 |
import itertools
N,M=list(map(int,input().split()))
ab=list(list(map(int,input().split())) for _ in range(M))
l=list(l for l in range(1,N+1))
numlist=list(itertools.permutations(l))
ans=0
for I in numlist:
if I[0]==1 and all(sorted([I[j],I[j+1]]) in ab for j in range(N-1)):
ans+=1
print(ans)
| import itertools
n, m = list(map(int, input().split()))
path = [[False] * n for i in range(n)]
for i in range(m):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
path[a][b] = True
path[b][a] = True
ans = 0
for i in itertools.permutations(list(range(n)), n):
if i[0] == 0:
for j in range(n):
if j == n - 1:
ans += 1
break
if not path[i[j]][i[j + 1]]:
break
print(ans) | p03805 |
from copy import deepcopy
def solve(road, num, ans, n):
pattern = 0
test = deepcopy(road)
if ans.count(str(num)) > 1:
return 0
if len(ans) is n:
return 1
if len(road[num - 1]) == int(0):
return 0
else:
for i in range(len(road[num - 1])):
tmp = test[num - 1][-1]
if tmp is not 0:
word = ans + str(tmp)
test[num - 1].pop()
pattern += solve(test, tmp, word, n)
return pattern
N, M = [int(i) for i in input().split()]
town = []
for i in range(N):
town.append(deepcopy([]))
for i in range(M):
a, b = [int(i) for i in input().split()]
town[a - 1].append(b)
town[b - 1].append(a)
print((solve(town, 1, '1', N)))
| from copy import deepcopy
def solve(road, num, ans, n):
pattern = 0
test = deepcopy(road)
for s in test:
if num in s:
s.remove(num)
if len(ans) is n:
return 1
if len(test[num - 1]) == int(0):
return 0
else:
for i in range(len(test[num - 1])):
tmp = test[num - 1][i]
if tmp is not 0:
word = ans + str(tmp)
pattern += solve(test, tmp, word, n)
return pattern
N, M = [int(i) for i in input().split()]
town = []
for i in range(N):
town.append(deepcopy([]))
for i in range(M):
a, b = [int(i) for i in input().split()]
if a is not 1 or b is not 1:
town[a - 1].append(b)
town[b - 1].append(a)
print((solve(town, 1, '1', N)))
| p03805 |
from copy import deepcopy
def solve(road, num, ans, n):
pattern = 0
test = deepcopy(road)
for s in test:
if num in s:
s.remove(num)
if len(ans) is n:
return 1
if len(test[num - 1]) == int(0):
return 0
else:
for i in range(len(test[num - 1])):
tmp = test[num - 1][i]
if tmp is not 0:
word = ans + str(tmp)
pattern += solve(test, tmp, word, n)
return pattern
N, M = [int(i) for i in input().split()]
town = []
for i in range(N):
town.append(deepcopy([]))
for i in range(M):
a, b = [int(i) for i in input().split()]
if a is not 1 or b is not 1:
town[a - 1].append(b)
town[b - 1].append(a)
print((solve(town, 1, '1', N)))
| N, M = [int(i) for i in input().split()]
road = [list() for i in range(N + 1)]
for i in range(M):
a, b = [int(i) for i in input().split()]
road[a].append(b)
road[b].append(a)
def solve(before, visited, now):
visited.append(now)
if len(visited) is N:
return 1
pattern = 0
for way in road[now]:
if way is now:
continue
if way in visited:
continue
pattern += solve(now, visited[:], way)
return pattern
print((solve(0, [], 1)))
| p03805 |
N,M=list(map(int,input().split()))
edges=[[] for _ in range(N)]
for i in range(M):
a,b=list(map(int,input().split()))
edges[a-1]+=[b-1]
edges[b-1]+=[a-1]
vis=[1]+[0]*(N-1)#訪問フラグ
ans=0
def DFS(v):
global ans
if vis==[1]*N:
ans+=1
return 0
for u in edges[v]:
if vis[u]==0:
vis[u]=1
DFS(u)
vis[u]=0
else: return 0
DFS(0)
print(ans) | N,M=list(map(int,input().split()))
edges=[[] for _ in range(N)]
for i in range(M):
a,b=list(map(int,input().split()))
edges[a-1]+=[b-1]
edges[b-1]+=[a-1]
vis=[1]+[0]*(N-1)#訪問フラグ
def DFS(v):
if vis==[1]*N:
return 1
ret=0
for u in edges[v]:
if vis[u]==0:
vis[u]=1
ret+=DFS(u)
vis[u]=0
else: return ret
print((DFS(0))) | p03805 |
import itertools
N, M = list(map(int, input().split()))
adj_matrix = [[0]* N for _ in range(N)]
for i in range(M): #隣接行列
a, b = list(map(int, input().split()))
adj_matrix[a-1][b-1] = 1
adj_matrix[b-1][a-1] = 1
cnt = 0
for each in itertools.permutations(list(range(N))):
if each[0] != 0:
break
factor = 1
for i in range(N-1):
factor *= adj_matrix[each[i]][each[i+1]]
cnt += factor
print(cnt) | N, M = list(map(int, input().split()))
matrix=[[0]*N for i in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
matrix[a-1][b-1]=1
matrix[b-1][a-1]=1
import itertools
count=0
for i in itertools.permutations(list(range(N))):
if i[0]==0:
result=1
for j in range(N-1):
result*=matrix[i[j]][i[j+1]]
if result==1:
count+=1
else:
break
print(count) | p03805 |
import copy
n, m = list(map(int, input().split()))
adjacent_list = [[] for i in range(n+1)]
for i in range(m):
a, b = list(map(int, input().split()))
adjacent_list[a].append(b)
adjacent_list[b].append(a)
ans = 0
def dfs(node, finished):
#print("node {} finished {}".format(node, finished))
finished.add(node)
global ans
if len(finished) == n:
ans += 1
else:
for i in adjacent_list[node]:
if i not in finished:
passed = copy.deepcopy(finished)
dfs(i, passed)
dfs(1,set([1]))
print(ans)
| import copy
n, m = list(map(int, input().split()))
adjacent_list = [[] for i in range(n+1)]
for i in range(m):
a, b = list(map(int, input().split()))
adjacent_list[a].append(b)
adjacent_list[b].append(a)
ans = 0
def dfs(node,f):
f.add(node)
global ans
if len(f) == n:
ans += 1
else:
for i in adjacent_list[node]:
if i not in f:
k = copy.deepcopy(f)
dfs(i,k)
dfs(1,set())
print(ans) | p03805 |
import copy
n, m = list(map(int, input().split()))
adjacent_list = [[] for i in range(n+1)]
for i in range(m):
a, b = list(map(int, input().split()))
adjacent_list[a].append(b)
adjacent_list[b].append(a)
ans = 0
def dfs(node,f):
f.add(node)
global ans
if len(f) == n:
ans += 1
else:
for i in adjacent_list[node]:
if i not in f:
k = copy.deepcopy(f)
dfs(i,k)
dfs(1,set())
print(ans) | n, m = list(map(int, input().split()))
adjacent_list = [[] for i in range(n+1)]
for i in range(m):
a, b = list(map(int, input().split()))
adjacent_list[a].append(b)
adjacent_list[b].append(a)
ans = 0
def dfs(node,f):
global ans
if len(f) == n:
ans += 1
else:
for i in adjacent_list[node]:
if i not in f:
k = f | set([i])
dfs(i,k)
dfs(1,set([1]))
print(ans) | p03805 |
# -*- coding: utf-8 -*-
import copy
n,m = list(map(int,input().split()))
rinset = [[0]*(n+1) for _ in range(n+1)]
for _ in range(m):
a,b = list(map(int,input().split()))
rinset[a][b]=b
rinset[b][a]=a
cnt = 0
def solve(start,visitted):
global cnt
visitted = copy.deepcopy(visitted)
visitted.append(start)
if len(visitted) == n:
cnt+=1
return
next_start=[i for i in rinset[start] if (i>1 and i not in visitted)]
for i in next_start:
solve(i,visitted)
solve(1,[])
print(cnt)
| # -*- coding: utf-8 -*-
n,m = list(map(int,input().split()))
ab = [list(map(int,input().split())) for i in range(m)]
#逆順にしたもの追加
ab += [[b,a] for a,b in ab]
#辺id付きで、idがfrom,abi[from]=[to1,to2,...] のリスト
abi = [[] for _ in range(n+1)]
for i,(a,b) in enumerate(ab):
abi[a].append(b)
#再起のlimitを上げる
import sys
sys.setrecursionlimit(4100000)
def dfs(idx=1,visitted=[1],cnt=1):
ret = 0
if cnt==n:
return 1
for to in abi[idx]:
if to not in visitted:
ret += dfs(to,visitted+[to],cnt+1)
return ret
print((dfs())) | p03805 |
import itertools
N, M = list(map(int, input().split()))
E = [[] for i in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
E[a].append(b)
E[b].append(a)
count = 0
for V in itertools.permutations(list(range(1, N))):
if V[0] in E[0] and all(V[i] in E[V[i-1]] for i in range(1, N-1)):
count += 1
print(count)
| from itertools import permutations
def int0(s):
return int(s) - 1
def main():
N, M = list(map(int, input().split()))
edges = [tuple(map(int0, input().split())) for _ in range(M)]
to = [[False]*N for _ in range(N)]
for a, b in edges:
to[a][b] = True
to[b][a] = True
ans = 0
for p in permutations(list(range(1, N))):
if to[0][p[0]] and all(to[p[i]][p[i+1]] for i in range(N-2)):
ans += 1
print(ans)
if __name__ == "__main__":
main() | p03805 |
import itertools
N, M = list(map(int, input().split()))
edges = [list([int(x) - 1 for x in input().split()]) for _ in range(M)]
res = 0
if M < N - 1:
print(res)
else:
for path in itertools.permutations(edges, N - 1):
vertex = [True] * N
v = 0
vertex[v] = False
for edge in path:
if v in edge:
nv = edge[0] if v == edge[1] else edge[1]
if vertex[nv]:
vertex[nv] = False
v = nv
continue
break
else:
res += 1
print(res)
| N, M = list(map(int, input().split()))
edges = [[] for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
edges[a - 1].append(b - 1)
edges[b - 1].append(a - 1)
def dfs(node, track):
if len(track) == N:
global res
res += 1
else:
for dst in [x for x in edges[node] if x not in track]:
dfs(dst, track + tuple([dst]))
res = 0
dfs(0, tuple([0]))
print(res)
| p03805 |
import itertools
N, M = list(map(int, input().split()))
edges = [tuple([int(x) - 1 for x in input().split()]) for _ in range(M)]
res = 0
if M < N - 1:
print(res)
else:
for course in itertools.combinations(edges, N - 1):
num_of_v = [0] * N
for edge in course:
num_of_v[edge[0]] += 1
num_of_v[edge[1]] += 1
if num_of_v[0] != 1 and max(num_of_v) != 2:
continue
for root in itertools.permutations(course):
vertex = [False] + [True] * (N - 1)
v = 0
for edge in root:
if v in edge:
nv = edge[0] if v == edge[1] else edge[1]
if vertex[nv]:
vertex[nv] = False
v = nv
continue
break
else:
res += 1
print(res)
| def main():
import sys
from itertools import permutations
# readline = sys.stdin.buffer.readline
readlines = sys.stdin.readlines
N, M = list(map(int, input().split()))
edge = [[0] * N for _ in range(N)]
for s in readlines():
a, b = list(map(int, s.split()))
a -= 1; b -= 1
edge[a][b] = 1
edge[b][a] = 1
cnt = 0
for path in permutations(list(range(1, N))):
path = [0] + list(path)
for i in range(N - 1):
v = path[i]
nv = path[i + 1]
if edge[v][nv] == 0:
break
else:
cnt += 1
print(cnt)
if __name__ == "__main__":
main()
| p03805 |
import itertools
N,M=list(map(int,input().split()))
edges={tuple(sorted(map(int,input().split()))) for i in range(M)}
ans=0
for i in itertools.permutations(list(range(2,N+1)),N-1):
l=[1]+list(i)
ans+=sum(1 for edge in zip(l,l[1:]) if tuple(sorted(edge)) in edges)==N-1
print(ans) | import itertools
N,M=list(map(int,input().split()))
edges={tuple(sorted(map(int,input().split()))) for i in range(M)}
ans=0
for i in itertools.permutations(list(range(2,N+1))):
l=[1]+list(i)
ans+=sum(1 for edge in zip(l,l[1:]) if tuple(sorted(edge)) in edges)==N-1
print(ans) | p03805 |
import copy
n, m = list(map(int, input().split()))
ab = [list(map(int, input().split())) for _ in range(m)]
cnt = 0
fin = set([i + 1 for i in range(n)])
def path(now, edges, past):
global cnt
if set(past) == fin:
cnt += 1
return 0
for i in range(len(edges)):
if now == edges[i][0] and edges[i][1] not in past:
new_now = edges[i][1]
new_edges = copy.deepcopy(edges)
new_past = copy.deepcopy(past)
new_edges.pop(i)
new_past.append(edges[i][1])
# print("now", now, "edges", edges, "new", new_edges, "past", past, "cnt", cnt)
path(new_now, new_edges, new_past)
elif now == edges[i][1] and edges[i][0] not in past:
new_now = edges[i][0]
new_edges = copy.deepcopy(edges)
new_past = copy.deepcopy(past)
new_edges.pop(i)
new_past.append(edges[i][0])
# print("now", now, "edges", edges, "new", new_edges, "past", past, "cnt", cnt)
path(new_now, new_edges, new_past)
for i in range(m):
if ab[i][0] == 1:
edges = copy.deepcopy(ab)
edges.pop(i)
path(ab[i][1], edges, [1, ab[i][1]])
elif ab[i][1] == 1:
edges = copy.deepcopy(ab)
edges.pop(i)
path(ab[i][0], edges, [1, ab[i][0]])
print(cnt)
| import itertools
n, m = list(map(int, input().split()))
ab = set()
for _ in range(m):
a, b = list(map(int, input().split()))
ab.add((a, b))
ab.add((b, a))
cnt = 0
for x in itertools.permutations(list(range(1, n + 1))):
if x[0] != 1:
break
flag = True
for i in range(len(x)-1):
if (x[i], x[i + 1]) not in ab:
flag = False
break
if flag:
cnt += 1
print(cnt)
| p03805 |
N,M = list(map(int,input().split()))
vertex = [[0 for j in range(N+1)] for i in range(N+1)]
AB = [list(map(int,input().split())) for _ in range(M)]
for i in range(M):
a,b = AB[i]
vertex[a][b] = 1
vertex[b][a] = 1
from itertools import permutations
ans = 0
for v in permutations([i+2 for i in range(N-1)], N-1):
v = [1] + list(v)
canmake = 1
for j in range(N-1):
if not vertex[v[j]][v[j+1]]:
canmake = 0
break
if canmake:
ans += 1
print(ans) | N,M = list(map(int,input().split()))
vertex = [[0 for j in range(N+1)] for i in range(N+1)]
for i in range(M):
a,b = list(map(int,input().split()))
vertex[a][b] = 1
vertex[b][a] = 1
from itertools import permutations
ans = 0
for v in permutations([i+2 for i in range(N-1)], N-1):
v = [1] + list(v)
canmake = 1
for j in range(N-1):
if not vertex[v[j]][v[j+1]]:
canmake = 0
break
if canmake:
ans += 1
print(ans) | p03805 |
import itertools
N,M=list(map(int,input().split()))
edges={tuple(sorted(map(int,input().split()))) for i in range(M)}
ans=0
for i in itertools.permutations(list(range(2,N+1)),N-1):
l=[1]+list(i)
ans+=sum(1 for edge in zip(l,l[1:]) if tuple(sorted(edge)) in edges)==N-1
print(ans) | import itertools
N,M=list(map(int,input().split()))
edges=set()
for _ in range(M):
a,b =list(map(int,input().split()))
edges.add((a,b))
edges.add((b,a))
answer=0
for p in itertools.permutations(list(range(1,N+1))):
if p[0] !=1:
continue
bl=True
for i in range(N-1):
if(p[i],p[i+1]) not in edges:
bl =False
break
if bl:
answer +=1
print(answer) | p03805 |
N, M = list(map(int, input().split()))
v = []
for i in range(M):
line = list(map(int, input().split()))
v.append([x - 1 for x in line])
conn = []
for _ in range(N):
conn.append([False] * N)
visited = [False] * N
for start, end in v:
conn[start][end] = conn[end][start] = True
def dfs(now, depth):
if visited[now]:
return 0
if depth == N - 1:
return 1
visited[now] = True
ret = 0
for i in range(N):
if conn[now][i]:
ret += dfs(i, depth + 1)
visited[now] = False
return ret
print((dfs(0,0))) | N, M = list(map(int, input().split()))
d = [[False for i in range(N)] for i in range(N)]
visited = [False] * N
for i in range(M):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
d[a][b] = True
d[b][a] = True
def dfs(now, depth):
if visited[now]:
return 0
if depth == N - 1:
return 1
ret = 0
visited[now] = True
for i in range(N):
if d[now][i]:
ret += dfs(i, depth + 1)
visited[now] = False
return ret
print((dfs(0,0))) | p03805 |
import itertools
def sonzai(path, start, goal):
for i in path:
if start in i:
if start > goal:
if i[0] == goal:
return True
else:
if i[1] == goal:
return True
return False
n, m = list(map(int, input().split()))
path = []
for i in range(m):
a, b = list(map(int, input().split()))
path.append([a, b])
ans = 0
for i in itertools.permutations(list(range(2, n + 1))):
if not sonzai(path, 1, i[0]):
continue
for j in range(n - 1):
if j == n - 2:
ans += 1
break
if not sonzai(path, i[j], i[j + 1]):
break
print(ans) | import itertools
n, m = list(map(int, input().split()))
graph = [[0 for i in range(n)] for j in range(n)]
for i in range(m):
a, b = list(map(int, input().split()))
graph[a - 1][b - 1] = 1
graph[b - 1][a - 1] = 1
ans = 0
for i in itertools.permutations(list(range(2, n + 1))):
if not graph[0][i[0] - 1]:
continue
for j in range(n - 1):
if j == n - 2:
ans += 1
break
if not graph[i[j] - 1][i[j + 1] - 1]:
break
print(ans) | p03805 |
import itertools as it
N, M = list(map(int, input().split()))
graph = [[] for i in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
a, b = a - 1, b - 1
graph[a].append(b)
graph[b].append(a)
ans = 0
for path in it.permutations(list(range(N))):
if path[0] != 0:
continue
is_connected = True
for ith_edge in range(len(path) - 1):
if path[ith_edge + 1] not in graph[path[ith_edge]]:
is_connected = False
break
if is_connected:
ans += 1
print(ans)
| import itertools as it
N, M = list(map(int, input().split()))
graph = [[] for i in range(N)]
for i in range(M):
a, b = list(map(int, input().split()))
a, b = a - 1, b - 1
graph[a].append(b)
graph[b].append(a)
ans = 0
for path in it.permutations(list(range(N))):
if path[0] != 0:
break
is_connected = True
for ith_edge in range(len(path) - 1):
if path[ith_edge + 1] not in graph[path[ith_edge]]:
is_connected = False
break
if is_connected:
ans += 1
print(ans)
| p03805 |
from itertools import permutations
def main():
n, m = list(map(int, input().split()))
edge = set()
for _ in range(m):
a, b = [int(x)-1 for x in input().split()]
edge.add((a, b))
edge.add((b, a))
#全ノード間に辺が張っていると仮定する
#このとき全てのノードを廻る順番は順列の数だけある
#ここから条件を絞って数えるべきものを数えていく
#ノードを廻る順を構成する
node_num = []
for i in range(n):
node_num.append(i)
cnt = 0
for p in permutations(node_num):
#数える経路は始点が0である
if p[0] == 0:
#この順列pの通りに辿れるように辺が張っているならこの経路は数えるべき経路である
flag = True
for i in range(n-1):
#この順列のあるノード間に辺が存在しないならこの経路は不可能
if (p[i], p[i+1]) not in edge:
flag = False
if flag:
cnt += 1
print(cnt)
main() | #python3
from itertools import permutations
def main():
n, m = list(map(int, input().split()))
edge = set()
for _ in range(m):
a, b = list(map(int, input().split()))
edge.add((a-1, b-1))
edge.add((b-1, a-1))
node = []
for i in range(n):
node.append(i)
cnt = 0
for p in permutations(node):
if p[0] == 0:
f = True
for j in range(n-1):
if (p[j], p[j+1]) not in edge:
f = False
if f:
cnt += 1
print(cnt)
main()
| p03805 |
from itertools import permutations
n, m = list(map(int, input().split()))
edges = [tuple(map(int, input().split())) for _ in range(m)]
ans = 0
for i in permutations(list(range(2, n+1)), n-1):
load = [1]+list(i)
ans += sum(1 for edge in zip(load, load[1:])
if tuple(sorted(edge)) in edges) == n-1
print(ans)
| from itertools import permutations
n, m = list(map(int, input().split()))
edges = {tuple(map(int, input().split())) for _ in range(m)}
ans = 0
for i in permutations(list(range(2, n+1)), n-1):
load = [1]+list(i)
ans += sum(1 for edge in zip(load, load[1:])
if tuple(sorted(edge)) in edges) == n-1
print(ans)
| p03805 |
from sys import stdin
def dfs(e, ans, done, N, graph):
if (1 << N) - 1 == done:
ans += 1
return ans
for s in graph[e]:
if done >> s & 1:
continue
done ^= 1 << s
ans = dfs(s, ans, done, N, graph)
done ^= 1 << s
return ans
def main():
lines = stdin.readlines()
N, M = list(map(int, lines[0].split()))
graph = [[] for i in range(N)]
for i in range(1, M + 1):
a, b = [int(x) - 1 for x in lines[i].split()]
# 0-based indexing
graph[a].append(b)
graph[b].append(a)
ans = 0
print((dfs(0, ans, 1, N, graph)))
return
main()
| from sys import stdin
N = int()
memo = {}
graph = []
def dfs(e, done):
if (1 << N) - 1 == done:
return 1
key = (e, done)
if key in memo:
return memo[key]
ret = 0
for s in graph[e]:
if done >> s & 1:
continue
done ^= 1 << s
ret += dfs(s, done)
done ^= 1 << s
memo[key] = ret
return ret
def main():
lines = stdin.readlines()
global N
N, M = list(map(int, lines[0].split()))
global graph
graph = [[] for i in range(N)]
for i in range(1, M + 1):
a, b = [int(x) - 1 for x in lines[i].split()]
# 0-based indexing
graph[a].append(b)
graph[b].append(a)
print((dfs(0, 1)))
return
main()
| p03805 |
n,m=list(map(int,input().split()))
road=[[] for _ in range(n+1)]
for i in range(m):
a,b=list(map(int,input().split()))
road[a].append(b)
road[b].append(a)
dp=[[0]*(n+1) for _ in range(2**n)]
dp[1][1]=1
for i in range(1,2**n):
for j in range(1,n+1):
for k in road[j]:
if not (i>>(k-1))&1:
dp[i+2**(k-1)][k]+=dp[i][j]
print((sum(dp[2**n-1])))
| n,m=list(map(int,input().split()))
root=[[] for _ in range(n+1)]
for i in range(m):
a,b=list(map(int,input().split()))
root[a].append(b)
root[b].append(a)
s=[0]*(n+1)
s[0]=1
s[1]=1
ans=0
def f(a,x):
global ans
for i in root[a]:
if x[i]==0:
x[i]=1
f(i,x)
x[i]=0
if x.count(1)==n+1:
ans+=1
f(1,s)
print(ans)
| p03805 |
n, m = list(map(int, input().split()))
graph = [[] for _ in range(n + 1)]
for _ in range(m):
a, b = list(map(int, input().split()))
graph[a].append(b)
graph[b].append(a)
visit = [0] * (n + 1)
def dfs(now, depth):
if visit[now]:
return 0
if depth == n:
return 1
count = 0
visit[now] = 1
if graph[now]:
for i in graph[now]:
count += dfs(i, depth + 1)
visit[now] = 0
return count
ans = dfs(1, 1)
print(ans)
| n, m = list(map(int, input().split()))
graph = [[] for _ in range(n + 1)]
for _ in range(m):
a, b = list(map(int, input().split()))
graph[a].append(b)
graph[b].append(a)
visit = [0] * (n + 1)
ans = 0
def dfs(now, depth):
global ans
if visit[now]:
pass
if depth == n:
ans += 1
visit[now] = 1
if graph[now]:
for i in graph[now]:
if visit[i] == 0:
dfs(i, depth + 1)
visit[now] = 0
dfs(1, 1)
print(ans)
| p03805 |
n,m = list(map(int,input().split()))
graph = [[]for i in range(n)]
for i in range(m):
a,b = list(map(int,input().split()))
a -=1
b-=1
graph[a].append(b)
graph[b].append(a)
def all_visited(l):
a = 0
for i in range(n):
if l[i]:
a+=1
if a == n:
return 1
else: return 0
def dfs(now):
ans = 0
visited[now] = 1
if all_visited(visited):
return 1
for next in graph[now]:
if visited[next]:continue
ans += dfs(next)
visited[next] =0
return ans
visited = [0]*n
print((dfs(0))) | import sys
sys.setrecursionlimit(10**8)
n,m = list(map(int,input().split()))
graph = [[]for i in range(n)]
visited = [0]*n
def all_v(visited):
cnt = 0
for x in visited:cnt+=x
return cnt == n
def dfs(now):
visited[now] = 1
if all_v(visited):return 1
res = 0
for next in graph[now]:
if visited[next]:continue
res += dfs(next)
visited[next] = 0
return res
for i in range(m):
a,b = list(map(int,input().split()))
a-=1
b -= 1
graph[a].append(b)
graph[b].append(a)
print((dfs(0)))
| p03805 |
N,M=list(map(int,input().split()))
import copy
a=[0]*M
b=[0]*M
for i in range(M):
a[i],b[i]=list(map(int,input().split()))
D=[[1]]
def route(D):
E=[]
D1=copy.deepcopy(D)
for j in range(len(D)):
x=D[j][-1]
for i in range(M):
if a[i]==x:
if not b[i] in D1[j]:
D=copy.deepcopy(D1)
D[j].append(b[i])
E.append(D[j])
elif b[i]==x:
if not a[i] in D1[j]:
D=copy.deepcopy(D1)
D[j].append(a[i])
E.append(D[j])
return E
for i in range(N-1):
D=copy.deepcopy(route(D))
print((len(D)))
| N,M=list(map(int,input().split()))
import copy
a=[0]*M
b=[0]*M
for i in range(M):
a[i],b[i]=list(map(int,input().split()))
D=[[1]]
def route(D):
E=[]
D1=copy.deepcopy(D)
for j in range(len(D)):
x=D[j][-1]
for i in range(M):
if a[i]==x:
if not b[i] in D1[j]:
D[j]=copy.deepcopy(D1[j])
D[j].append(b[i])
E.append(D[j])
elif b[i]==x:
if not a[i] in D1[j]:
D[j]=copy.deepcopy(D1[j])
D[j].append(a[i])
E.append(D[j])
return E
for i in range(N-1):
D=copy.deepcopy(route(D))
print((len(D)))
| p03805 |
N,M=list(map(int,input().split()))
import copy
a=[0]*M
b=[0]*M
for i in range(M):
a[i],b[i]=list(map(int,input().split()))
D=[[1]]
def route(D):
E=[]
D1=copy.deepcopy(D)
for j in range(len(D)):
x=D[j][-1]
for i in range(M):
if a[i]==x:
if not b[i] in D1[j]:
D[j]=copy.deepcopy(D1[j])
D[j].append(b[i])
E.append(D[j])
elif b[i]==x:
if not a[i] in D1[j]:
D[j]=copy.deepcopy(D1[j])
D[j].append(a[i])
E.append(D[j])
return E
for i in range(N-1):
D=copy.deepcopy(route(D))
print((len(D)))
| def bit_DP(N,Adj):
dp=[[0]*N for i in range(1<<N)]
dp[1][0]=1
for S in range(1<<N):
for v in range(N):
if (S&(1<<v))==0:
continue
sub=S^(1<<v)
for u in range(N):
if (sub&(1<<u)) and (Adj[u][v]):
dp[S][v]+=dp[sub][u]
ans=sum(dp[(1<<N)-1][u] for u in range(1,N))
return ans
def main():
N,M=list(map(int,input().split()))
Adj=[[0]*N for i in range(N)]
for _ in range(M):
a,b=list(map(int,input().split()))
Adj[a-1][b-1]=1
Adj[b-1][a-1]=1
ans=bit_DP(N,Adj)
print(ans)
if __name__=='__main__':
main() | p03805 |
import sys
sys.setrecursionlimit(1000000)
N, M = list(map(int, input().split()))
ab = [list([int(x)-1 for x in input().split()]) for _ in range(M)]
adlist = [[] for _ in range(N)]
for a, b in ab:
adlist[a] += [b]
adlist[b] += [a]
used = [0]*N
global ans
ans = 0
def dfs(v):
global ans
used[v] = 1
if sum(used) == N:
ans += 1
return
for u in adlist[v]:
if used[u] == 0:
used[u] = 1
dfs(u)
used[u] = 0
return
dfs(0)
print(ans) | import sys
sys.setrecursionlimit(1000000)
n, m = list(map(int, input().split()))
graph = [[] for _ in range(n)]
for _ in range(m):
a, b = [int(x)-1 for x in input().split()]
graph[a] += [b]
graph[b] += [a]
used = [0]*n
global ans
ans = 0
def dfs(u):
global ans
used[u] = 1
if sum(used) == n:
ans += 1
return
for v in graph[u]:
if used[v] == 0:
used[v] = 1
dfs(v)
used[v] = 0
return
dfs(0)
print(ans)
| p03805 |
n, m = list(map(int, input().split()))
paths = set()
for i in range(m) :
_a, _b = list(map(int, input().split()))
paths.add((_a - 1, _b - 1))
paths.add((_b - 1, _a - 1))
full_mask = "".join(["1" for x in range(n)])
zero_mask = "".join(["0" for x in range(n)])
p_cnt = 0
def dfs(cur_idx, mask) :
global p_cnt
# set mask and do traverse
new_mask = list(mask)
new_mask[cur_idx] = "1"
new_mask = "".join(new_mask)
# print("DBG : ", cur_idx, new_mask, full_mask, new_mask == full_mask)
if new_mask == full_mask :
p_cnt += 1
else :
for i in range(n) :
# if cur_idx -> i in set and i not traversed yet..
if (cur_idx, i) in paths and mask[i] != "1" :
dfs(i, new_mask)
dfs(0, zero_mask)
print(p_cnt)
| n, m = list(map(int, input().split()))
paths = set()
zero_mask = "".join(["0" for x in range(n)])
full_mask = "".join(["1" for x in range(n)])
paths_cnt = 0
for i in range(m) :
_a, _b = list(map(int, input().split()))
paths.add((_a - 1, _b - 1))
paths.add((_b - 1, _a - 1))
def mask_idx(s, idx) :
newmask = s[:idx] + "1" + s[idx + 1:]
return newmask
def dfs(cur_idx, mask) :
global paths_cnt
new_mask = mask_idx(mask, cur_idx)
# print("DBG : ", cur_idx, new_mask, full_mask)
if new_mask == full_mask :
paths_cnt += 1
for i in range(n) :
if i != cur_idx and new_mask[i] != '1' and (cur_idx, i) in paths:
dfs(i, new_mask)
dfs(0, zero_mask)
print(paths_cnt)
| p03805 |
N, M = list(map(int, input().split()))
paths = set()
for i in range(M) :
_f, _t = list(map(int, input().split()))
paths.add((_f - 1, _t - 1))
paths.add((_t - 1, _f - 1))
zeromask = "".join(['0' for x in range(N)])
fullmask = "".join(['1' for x in range(N)])
cnt = 0
def do_mask(m, idx) :
return m[:idx] + '1' + m[idx + 1:]
def dfs(m, idx) :
global cnt
new_mask = do_mask(m, idx)
if new_mask == fullmask :
cnt += 1
else :
for i in range(N) :
if i != idx and m[idx] != '1' and (idx, i) in paths:
dfs(new_mask, i)
dfs(zeromask, 0)
print(cnt) | N, M = list(map(int, input().split()))
a, b = [], []
for i in range(M) :
_a, _b = list(map(int, input().split()))
a.append(_a - 1)
b.append(_b - 1)
zero_mask = "".join(['0' for x in range(N)])
full_mask = "".join(['1' for x in range(N)])
paths_cnt = 0
paths_set = set()
def do_mask(m, idx) :
newmask = m[:idx] + '1' + m[idx + 1:]
return newmask
def dfs(m, idx) :
global paths_cnt
# print("DBG, do dfs with : ", m, idx)
# do mask for current idx
newmask = do_mask(m, idx)
if newmask == full_mask :
paths_cnt += 1
else :
for i in range(N) :
# print("DBG2 : ", idx != i, newmask[i] != '1', (idx, i) in paths_set, (idx, i))
if idx != i and newmask[i] != '1' and (idx, i) in paths_set:
dfs(newmask, i)
# generate map
for i in range(M) :
paths_set.add((a[i], b[i]))
paths_set.add((b[i], a[i]))
dfs(zero_mask, 0)
print(paths_cnt) | p03805 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.