看了两天了,今天一下午就跟POJ1182卯上了,到处错,到出错,各种鄙视自己,万幸最后还是过了,happy一个
留个代码作纪念
package june;
import java.io.*;
public class Poj1182 {
public static void main(String[] args) throws IOException {
Poj1182 poj = new Poj1182();
BufferedReader read = new BufferedReader(new InputStreamReader(
System.in));
String[] tm = read.readLine().split(" ");
int N = new Integer(tm[0]);
int K = new Integer(tm[1]);
poj.initial(N);
int i = 0;
int count = 0;
if (K == 0)
System.out.println(count);
while (++i <= K) {
String[] tmp = read.readLine().split(" ");
int kind = new Integer(tmp[0]);
int animalA = new Integer(tmp[1]);
int animalB = new Integer(tmp[2]);
if (animalA > N || animalB > N) {
count++;
continue;
}
if (animalA == animalB) {
if (kind == 2)
count++;
continue;
}
int fa = poj.find(animalA);
int fb = poj.find(animalB);
if (fa == fb) {
if (kind == 1) {
if (poj.mod[animalA] != poj.mod[animalB])
count++;
} else {
if ((poj.mod[animalA] + 1) % 3 != poj.mod[animalB] % 3)
count++;
}
} else
poj.union(animalA, animalB, kind);
}
read.close();
System.out.println(count);
}
int[] parent;
int[] mod;
void union(int x, int y, int kind) {
int fx = find(x);
int fy = find(y);
if (fx != fy) {
if (mod[x] < mod[y]) {
parent[fx] = fy;
if (kind == 2)
mod[fx] = (mod[y] - mod[x] - 1 + 3) % 3;
else
mod[fx] = (mod[y] - mod[x]) % 3;
} else {
parent[fy] = fx;
if (kind == 2)
mod[fy] = (mod[x] - mod[y] + 1) % 3;
else
mod[fy] = (mod[x] - mod[y]) % 3;
}
}
}
int find(int x) {
if (x == parent[x])
return parent[x];
else {
int t = parent[x];
parent[x] = find(parent[x]);
mod[x] = (mod[x] + mod[t]) % 3;
}
return parent[x];
}
void initial(int n) {
parent = new int[n + 1];
mod = new int[n + 1];
for (int i = 1; i < n + 1; i++)
parent[i] = i;
}
}
话说Java在oj上可真耗时,Scanner必然TLE,无奈之下想起了某同学的Reader流大发,勉强过了,不过还是花了近3000ms,等有时间好好研究一下,一下午总算没白费啊,加油~~