Featured image of post 蓝桥杯P8064

蓝桥杯P8064

蓝桥杯P8064

题目:

image-20250409215501250image-20250409215526649

答案:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static List<Integer> [] list;
    static boolean flag=false;
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int m=sc.nextInt();
        list=new List[n+1];
         //初始化一下,不然会报错,节点从1开始
        for (int i = 0; i <= n ; i++) {
            list[i]=new ArrayList<>();
        }
        //首先是建无向图
        for (int i = 0; i <m ; i++) {
            int x=sc.nextInt();
            int y=sc.nextInt();
            list[x].add(y);
            list[y].add(x);
        }
        int x= sc.nextInt();
        int y= sc.nextInt();
        //先判断两点之间是否连通
        Set<Integer> set=new HashSet<>();
        set.add(x);
        flag=false;
        dfs(x,y,x,0,set);
        //假如不连通,直接输出-1
        if (!flag){
            System.out.println(-1);
        }else{
            int ans=0;
            for(int i=1;i<=n;i++){
                if(i==x||i==y||list[i].size()==0) continue;
                flag=false;
                set=new HashSet<>();
                set.add(x);
                dfs(x,y,x,i,set);
                if (!flag){
                    ans++;
                }
            }
            System.out.println(ans);
        }
    }
    public static void dfs(int s,int t,int u,int i,Set<Integer> set){
        if (u==t){
            flag=true;
        }else {
            for(int x: list[u]){
                if(set.contains(x)||x==i) continue;
                set.add(x);
                dfs(s,t,x,i,set);
            }
        }
    }
}
NovaBryan的博客
使用 Hugo 构建
主题 StackJimmy 设计