我正在为一个作业创建一个程序,该程序以以下格式从 System.in 获取输入:
Inky Pinky Blinky Clyde Luigi Mario Bowser
0 2
1 2
5 6
3 5
2 4
4 5
2 3
1 4
closefriends 1 2 4
第一行是人,数字是友谊。
该程序检查最后一行中列出的人是否处于“亲密友谊”中,他们都是朋友。
我将网络表示为一个事件矩阵,它通过了我们使用的测试站点上的所有测试,除了一个失败并出现“运行时错误”的测试。我知道这不是一个异常,因为捕获所有异常对错误没有任何影响,而捕获所有错误则可以。
这是代码:
public class CloseFriends {
// Contains edges represented as an incident matrix
private static boolean edges[][];
// Adds a directed edge between v1 and v2
// The method sorts the edges to reduce space used
public static void addEdge(int v1, int v2) {
if (v1 > v2) {
edges[v1][v2] = true;
}
else {
edges[v2][v1] = true;
}
}
// Creates a graph with V vertices
public static void createVertices(int V) {
edges = new boolean[V][V];
}
// Checks if an edge exists between v1 and v2
public static boolean isFriends(int v1, int v2) {
if (v1 > v2) {
return edges[v1][v2];
}
else {
return edges[v2][v1];
}
}
// Checks if an ArrayList of vertices is close friends
public static void closeFriends(ArrayList<Integer> vertices) {
int count = 0;
int size = vertices.size();
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (isFriends(vertices.get(i), vertices.get(j))) {
count++;
}
}
}
// The clique should contain n*(n-1)/2 edges for everyone to be connected
if (count == (size * (size - 1) / 2)) {
System.out.println("yes");
}
else {
System.out.println("no");
}
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
// Count vertices, and create that amount
int V = 0;
while (st.hasMoreTokens()) {
st.nextToken();
V++;
}
createVertices(V);
ArrayList<Integer> friends = new ArrayList<Integer>();
// While System.in has something to be read
while (in.ready()) {
// Read the line and add edges based on input, or run the algorithm
String edge = "";
edge = in.readLine();
if (edge != null) {
st = new StringTokenizer(edge);
if (!edge.startsWith("closefriends")) {
addEdge(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
}
else {
st.nextToken();
while (st.hasMoreTokens()) {
friends.add(Integer.parseInt(st.nextToken()));
}
}
}
}
closeFriends(friends);
}
}
谢谢!