并查集-一笔画优化
来源:互联网 发布:c语言 true 编辑:程序博客网 时间:2024/04/30 14:54
package 搜索.并查集;
import java.util.Scanner;
/*
* 1:使用num算出总的合并次数。
* 5个点,最少要保证合并5-1次才能保证图连通
* num<n-1;不连通
* num+1<n
* n-num>1
*/
public class 一笔画优化 {
static int[] pre;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n-- > 0) {
int p = sc.nextInt();
int q = sc.nextInt();
pre = new int[p + 1];
int arr[] = new int[p + 1];
for (int i = 1; i <= p; i++)
pre[i] = i;
int a, b;
int num = 0;// 优化1
for (int i = 0; i < q; i++) {
a = sc.nextInt();
b = sc.nextInt();
arr[a]++;
arr[b]++;
int x = find(a);
int y = find(b);
if (x != y) {
pre[x] = y;
num++;
}
}
if (p - num > 1)
System.out.println("No");
else {
num = 0;
for (int i = 1; i <= p; i++) {
if (num > 2)// 优化2
break;
num += (arr[i] % 2);
}
if (num == 0 || num == 2) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
private static int find(int a) {//优化3
if (a == pre[a])
return a;
return pre[a] = find(pre[a]);
}
}
import java.util.Scanner;
/*
* 1:使用num算出总的合并次数。
* 5个点,最少要保证合并5-1次才能保证图连通
* num<n-1;不连通
* num+1<n
* n-num>1
*/
public class 一笔画优化 {
static int[] pre;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n-- > 0) {
int p = sc.nextInt();
int q = sc.nextInt();
pre = new int[p + 1];
int arr[] = new int[p + 1];
for (int i = 1; i <= p; i++)
pre[i] = i;
int a, b;
int num = 0;// 优化1
for (int i = 0; i < q; i++) {
a = sc.nextInt();
b = sc.nextInt();
arr[a]++;
arr[b]++;
int x = find(a);
int y = find(b);
if (x != y) {
pre[x] = y;
num++;
}
}
if (p - num > 1)
System.out.println("No");
else {
num = 0;
for (int i = 1; i <= p; i++) {
if (num > 2)// 优化2
break;
num += (arr[i] % 2);
}
if (num == 0 || num == 2) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
private static int find(int a) {//优化3
if (a == pre[a])
return a;
return pre[a] = find(pre[a]);
}
}
0 0
- 并查集-一笔画优化
- 并查集-一笔画
- nyoj 一笔画(并查集)
- nyist 42一笔画问题(并查集+欧拉图)
- NYOJ42 一笔画问题 【欧拉回路】+【并查集】
- NYOJ--42一笔画问题【并查集】
- 一笔画问题(nyoj42)(并查集+欧拉图)
- NYOJ 42 一笔画问题 【欧拉图 + 并查集】
- 并查集 深搜 nyoj 42 一笔画问题
- 一笔画问题(并查集+无向欧拉图)
- ny 42 一笔画问题【欧拉路+并查集】
- nyoj--42--一笔画问题(并查集)
- nyoj-一笔画问题(欧拉图+并查集)
- NYOJ 42 一笔画问题 (DFS || 并查集)
- nyoj 一笔画问题 【并查集+欧拉】
- nyoj 一笔画问题(并查集,欧拉路)
- NYOJ42 一笔画问题(欧拉路+并查集)
- nyoj 一笔画(含并查集详解)
- SQL Server 排序函数 ROW_NUMBER和RANK 用法总结
- 并查集-国王的烦恼
- 并查集-一笔画
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 在生产环境使用Kuberntes一年后,我们总结了这些经验和教训
- 并查集-一笔画优化
- 数据库索引
- 安卓 闹钟demo
- Android笔记之seekTo
- EditText在手机弹出的软键盘中,将回车键变为搜索键和点击搜索键时,执行2次搜索解决
- 好雨云帮一周问答集锦(2017.02.13-2017.02.19)
- 关于android使用ksoap2报Caused by: java.lang.ClassCastException: org.ksoap2.SoapFault cannot be cast to or
- 割点-危险系数
- 2017读书雷达