同样的代码,我换了个输入方式就运行错误?
试了n多种方法测试,想不明白,,,哪位大佬懂,,,求求求解惑
正确代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class Main {
static int[] link, lazy, value;
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(System.out);
in.nextToken();
int n = (int)in.nval;
in.nextToken();
int m = (int)in.nval;
value = new int[n + 1];
lazy = new int[n + 1];
link = new int[n + 1];
for (int i = 1; i <= n; i++) link[i] = i;
while (m-- > 0) {
in.nextToken();
int i = (int)in.nval;
in.nextToken();
int v = (int)in.nval;
in.nextToken();
int w = (int)in.nval;
if (i == 1) {
v = find(v);
w = find(w);
if (v != w) {
link[v] = w;
lazy[v] = value[v] - value[w];
}
} else value[find(v)] += w;
}
for (int i = 1; i <= n; i++)
out.print((value[find(i)] + lazy[i]) + " ");
out.close();
}
static int find(int x) {
if (link[x] != x) {
int t = link[x];
link[x] = find(link[x]);
lazy[x] += lazy[t];
}
return link[x];
}
}
换称Scanner就运行错误,本地运行没问题
import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
static int[] link, lazy, value;
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
value = new int[n + 1];
lazy = new int[n + 1];
link = new int[n + 1];
for (int i = 1; i <= n; i++) link[i] = i;
while (m-- > 0) {
int i = in.nextInt();
int v = in.nextInt();
int w = in.nextInt();
if (i == 1) {
v = find(v);
w = find(w);
if (v != w) {
link[v] = w;
lazy[v] = value[v] - value[w];
}
} else value[find(v)] += w;
}
for (int i = 1; i <= n; i++)
out.print((value[find(i)] + lazy[i]) + " ");
out.close();
in.close();
}
static int find(int x) {
if (link[x] != x) {
int t = link[x];
link[x] = find(link[x]);
lazy[x] += lazy[t];
}
return link[x];
}
}
原题链接
|