package lanqiao;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class haha {
public static int ans = 0;
public static int[][] M = new int[7][78];
public static int[] p = new int[7];
public static void init() {
M[0][1] = M[1][0] = M[0][5] = M[5][0] = 1;
M[1][2] = M[2][1] = M[1][6] = M[6][1] = 1;
M[2][3] = M[3][2] = M[2][6] = M[6][2] = 1;
M[4][3] = M[3][4] = 1;
M[4][5] = M[5][4] = M[4][6] = M[6][4] = 1;
M[5][6] = M[6][5] = 1;
for(int i = 0; i < 7; i++)
p[i] = i;
}
public static void union(int a, int b) {
int xroot = find(a);
int yroot = find(b);
if(xroot != yroot)
p[xroot] = yroot;
}
public static int find(int a) {
if(p[a] == a)
return a;
return p[a] = find(p[a]);
}
public static boolean puan(List<Integer> list) {
init();//每一次都要判断是否是连同的,一次使用过之后,我们的连通块就是这一次的集合,下次再次判断的时候,我们需要集合恢复初始化;
for(int i = 0; i < list.size(); i++) {
for(int j = i + 1; j < list.size(); j++) {
int a = list.get(i);
int b = list.get(j);
if(M[a][b] == 1)
union(a, b);
}
}
if(!list.isEmpty()) {
int a = find(list.get(0));
for(int i = 0; i < list.size(); i++) {
int b = find(list.get(i));
if(a != b) return false;
}
return true;
}
return false;
}
public static void dfs(List<Integer> list, int u) {
if(u == 7) {
if(puan(list)) ans++;
return ;
}
list.add(u);
dfs(list, u + 1);
list.remove(list.size() - 1);
dfs(list, u + 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
dfs(list, 0);
System.out.println(ans);
sc.close();
}
}
2020年 第11届 蓝桥杯 Java B组七段码并查集
最新推荐文章于 2024-08-29 18:44:48 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)