poj2524(并查集)
来源:互联网 发布:mac ndk下载地址 编辑:程序博客网 时间:2024/04/30 13:50
点击打开题目链接
大意:多组数据。每组数据中,n个学生,每个学生信最多一种教。给出m对学生信息,每对中两个学生信的教一样。
求这n个学生信教种数最多有多少。
思路:并查集,基础练手题
代码如下:
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.StringTokenizer;class Reader {static BufferedReader reader;static StringTokenizer tokenizer;static void init(InputStream input) {reader = new BufferedReader(new InputStreamReader(input));tokenizer = new StringTokenizer("");}static String next() throws IOException {while (!tokenizer.hasMoreTokens()) {tokenizer = new StringTokenizer(reader.readLine());}return tokenizer.nextToken();}static int nextInt() throws IOException {return Integer.parseInt(next());}}public class Main {/** * @param args */static int ans, n, m, pa, pb, u, v, casenum;static int p[], rank[];private static int father(int u) {if (u == p[u])return u;p[u] = father(p[u]);return p[u];}private static void merge(int a, int b) {pa = father(a);pb = father(b);if (pa != pb) {if (rank[pa] < rank[pb])p[pa] = pb;elsep[pb] = pa;if (rank[pa] == rank[pb])rank[pa]++;}}public static void main(String[] args) throws IOException {// TODO Auto-generated method stubReader.init(System.in);p = new int[50001];rank = new int[50001];n = Reader.nextInt();m = Reader.nextInt();casenum = 0;while ((n != 0) || (m != 0)) {casenum++;for (int i = 1; i <= n; i++) {p[i] = i;rank[i] = 1;}for (int i = 1; i <= m; i++) {u = Reader.nextInt();v = Reader.nextInt();merge(u, v);}ans = 0;for (int i = 1; i <= n; i++)if (p[i] == i)ans++;System.out.println("Case " + casenum + ": " + ans);n = Reader.nextInt();m = Reader.nextInt();}}}
阅读全文
0 0
- POJ2524(并查集)
- poj2524(并查集)
- POJ2524-并查集
- poj2524 并查集
- poj2524 并查集
- POJ2524(并查集)
- POJ2524->并查集
- 并查集:poj2524:
- poj2524(并查集)
- POJ2524 并查集
- POJ2524(并查集)
- POJ2524 并查集应用
- POJ2524(简单并查集)
- [c] poj2524 并查集
- poj2524并查集模板
- POJ2524 Ubiquitous Religions 并查集
- 并查集简单小习题 poj2524
- 1poj2524(套模板并查集)
- ctags使用方法 ctags的使用方法
- 算法细节系列(23):回溯
- gdx 打包可执行 jar 不会包含源码 src 目录下的资源
- Kotlin
- java实现遍历树形菜单方法——Dao层
- poj2524(并查集)
- 通讯录第三版
- 使用maven 自动为 js/css加版本号
- UiAutomator 使用简介
- 读java编程那些事——计算机基础
- 总结/继承,多态
- TextView详解
- 随机从1~100中选出10个数并进行冒泡排序
- 关于mysql中字符编码