NC218914. OnAverageThey'rePurple
描述
输入描述
The first line contains two integer values N and M with and . The next M lines contain two integers and indicating an undirected edge between nodes and (, ).
All edges in the graph are unique.
输出描述
Output the maximum number of color changes Alice can force Bob to make on his route from node 1 to node N.
示例1
输入:
3 3 1 3 1 2 2 3
输出:
0
示例2
输入:
7 8 1 2 1 3 2 4 3 4 4 5 4 6 5 7 6 7
输出:
3
Python3(3.9) 解法, 执行用时: 687ms, 内存消耗: 23980K, 提交时间: 2021-03-07 15:00:11
from collections import deque n, m = [int(i) for i in input().split()] li = [[] for _ in range(n)] for i in range(m): a, b = [int(i) for i in input().split()] a -= 1 b -= 1 li[a].append(b) li[b].append(a) res = [float('inf') for _ in range(n)] res[0] = 0 que = deque([0]) while que: a = que.popleft() for b in li[a]: if res[a] + 1 < res[b]: res[b] = res[a] + 1 que.append(b) print(res[n-1] - 1)
C++(clang++11) 解法, 执行用时: 86ms, 内存消耗: 7024K, 提交时间: 2021-03-07 13:05:48
#include<bits/stdc++.h> using namespace std; const int N=1e5+5; vector<int>e[N]; int n,m; int dist[N],q[N]; int main(){ cin>>n>>m; while(m--){ int u,v; cin>>u>>v; e[u].push_back(v); e[v].push_back(u); } int he=0,ta=1; q[0]=1; dist[1]=1; while(he!=ta){ int u=q[he++]; for(auto v:e[u]){ if(dist[v]==0) dist[v]=dist[u]+1,q[ta++]=v; } } cout<<dist[n]-2; }