列表

详情


NC218914. OnAverageThey'rePurple

描述



Alice and Bob are playing a game on a simple connected graph with N nodes and M edges.

Alice colors each edge in the graph red or blue.

A path is a sequence of edges where each pair of consecutive edges have a node in common. If the first edge in the pair is of a different color than the second edge, then that is a ''color change.''

After Alice colors the graph, Bob chooses a path that begins at node 1 and ends at node N. He can choose any path on the graph, but he wants to minimize the number of color changes in the path. Alice wants to choose an edge coloring to maximize the number of color changes Bob must make. What is the maximum number of color changes she can force Bob to make, regardless of which path he chooses? 

输入描述

The first line contains two integer values N and M with  and . The next M lines contain two integers a_i and b_i indicating an undirected edge between nodes a_i and b_i (, ).

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;
}

上一题