明显一笔画问题,求欧拉路径,就是不知道为什么不能100,我用网上的几个大神的代码都没100,都是运行错误(RE)。估计是ccf那边的问题。
根据留言的反应是因为爆栈的问题。我重新写了个非递归的寻找欧拉路径方法,终于不是运行错误了,而是超时80分[哭] Java也是超时80分。。。所以应该是有两个测试用例数据太大了。。。用c++写就肯定100。
python 代码(递归):
import sys
sys.setrecursionlimit(10 ** 6)
def dfs(u):
for v in graph[u]:
key = str(min(u, v)) + ' ' + str(max(u, v))
if mp[key]:
mp[key] -= 1
dfs(v)
stack.append(u)
def has_euler_path():
odd_cnt = 0
for i, line in enumerate(graph):
if len(line) % 2 == 1:
odd_cnt += 1
start.append(i)
if odd_cnt == 0:
start.append(0)
return True if odd_cnt == 0 or odd_cnt == 2 else False
n, m = map(int, input().split())
graph = [[] for _ in range(n)]
stack = []
mp = {}
for i in range(m):
u, v = [int(e) - 1 for e in input().split()]
graph[u].append(v)
graph[v].append(u)
key = str(min(u, v)) + ' ' + str(max(u, v))
if key in mp:
mp[key] += 1
else:
mp[key] = 1
for i in range(n):
graph[i] = sorted(graph[i])
start = []
if has_euler_path() and 0 in start:
dfs(0)
if len(stack) == m + 1:
[print(e + 1, end=' ') for e in stack[::-1]]
else:
print(-1)
else:
print(-1)
python代码(非递归):
def get_path():
stack = [0]
while stack:
curnode = stack[-1]
for v in graph[curnode]:
key = str(min(curnode, v)) + ' ' + str(max(curnode, v))
if mp[key]:
mp[key] -= 1
stack.append(v)
break
else:
path.append(stack.pop())
def has_euler_path():
odd_cnt = 0
for i, line in enumerate(graph):
if len(line) % 2 == 1:
odd_cnt += 1
start.append(i)
if odd_cnt == 0:
start.append(0)
return True if odd_cnt == 0 or odd_cnt == 2 else False
n, m = map(int, input().split())
graph = [[] for _ in range(n)]
path = []
mp = {}
for i in range(m):
u, v = [int(e) - 1 for e in input().split()]
graph[u].append(v)
graph[v].append(u)
key = str(min(u, v)) + ' ' + str(max(u, v))
if key in mp:
mp[key] += 1
else:
mp[key] = 1
for i in range(n):
graph[i] = sorted(graph[i])
start = []
if has_euler_path() and 0 in start:
get_path()
if len(path) == m + 1:
[print(e + 1, end=' ') for e in path[::-1]]
else:
print(-1)
else:
print(-1)