POJ 1041 java语言

来源:互联网 发布:linux运维管理命令 编辑:程序博客网 时间:2024/06/05 19:28

说实话,本身就是个初学者,第2次做图相关的题,题意是读懂了,也知道是欧拉图,图论学过。但是用代码一点头绪都没有。

开始想着用一个二维数组来保存x,y的值吧!可是要怎么去遍历呢,如何递归呢?那后面的边又怎么用呢?各种困难(尽管网上写出来的都说很基础,我是各位要是拍,请轻拍呀),最后还是参考网上的代码。写完后,还是挺简单的,额貌似没什么要说的上代码吧

package poj1041;import java.io.IOException;import java.util.Scanner;public class Main {private static int mGst[];private static int mGed[];private static int mVst[];private static int mDeg[];private static int mPath[];private static int mMax_e;private static int mMax_v;private static int mStep;public static void main(String args[]) throws IOException {Scanner sc = new Scanner(System.in);int x, y, z, i;while ((x = sc.nextInt()) * (y = sc.nextInt()) != 0) {initialData();z = sc.nextInt();mGst[z] = x;mGed[z] = y;mDeg[x]++;mDeg[y]++;mMax_e++;mMax_v = x > y ? x : y;while ((x = sc.nextInt()) * (y = sc.nextInt()) != 0) {z = sc.nextInt();mGst[z] = x;mGed[z] = y;mDeg[x]++;mDeg[y]++;mMax_e++;mMax_v = x > y ? x : y;}if (!is_EulerG()) {System.out.println("Round trip does not exist.");continue;}DFS(mGst[1] > mGed[1] ? mGed[1] : mGst[1]);//John住在1街道的较小点for (i = mStep - 1; i > 0; i--) {System.out.printf("%d%c", mPath[i], i == 1 ? '\n' : ' ');}}}public static boolean is_EulerG() {for (int i = 1; i <= mMax_v; i++) {if (mDeg[i] % 2 != 0) {return false;}}return true;}public static void DFS(int v) {for (int i = 1; i <= mMax_e; i++) {if (mVst[i] == 0) {if (mGst[i] == v || mGed[i] == v) {mVst[i] = 1;DFS(mGst[i] + mGed[i] - v);mPath[mStep++] = i;}}}}public static void initialData() {mMax_e = 0;mMax_v = 0;mStep = 1;mGst = new int[1996];mGed = new int[1996];mVst = new int[1996];mDeg = new int[45];mPath = new int[1996];}}


原创粉丝点击