10個圖遍歷的問題及答案,有興趣的看看

PROBLEM :  Star Gates

Problem:  The Intelligent CargoExpress transport company of WorldZewa Planet
Allies (WZPA) services a number of planets in World Zewa.  Because of
monetary concerns, all of the cargo space ships are 'one-way.' That is, a
route from Planet Kaitaia to Planet Invercargill does not imply the
existence of a route from Planet Invercargill to Planet Kaitaia.  In fact,
even if both of these routes do happen to exist, they are distinct and are
not necessarily the same distance! The purpose of this problem is to help
the cargo transport company provide its customers with information about the
routes.  In particular, you will compute the distance along a certain route,
the number of different routes between two planets, and the shortest route
between two planets.

Input:  A directed graph where a node represents a planet and an edge
represents a route between two planets.  The weighting of the edge
represents the distance between the two planets.  A given route will never
appear more than once, and for a given route, the starting and ending planet
will not be the same planet.

Output: For test input 1 through 5, if no such route exists, output 'NO SUCH
ROUTE'.  Otherwise, follow the route as given; do not make any extra stops!
For example, the first problem means to start at planet A, then travel
directly to planet B (a distance of 5), then directly to planet C (a
distance of 4).
/n
/n
(Read from stdin,  fixed in code also acceptable. No need to validate.)
/n
AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7
/n


Expected Output:

Output #1: 9
Output #2: 5
Output #3: 13
Output #4: 22
Output #5: NO SUCH ROUTE
Output #6: 2
Output #7: 3
Output #8: 9
/nOutput #9: 9
Output #10: 7

/n
 
",1] ); //-->

1. The distance of the route A-B-C.
2. The distance of the route A-D.
3. The distance of the route A-D-C.
4. The distance of the route A-E-B-C-D.
5. The distance of the route A-E-D.
6. The number of trips starting at C and ending at C with a maximum of 3
stops.  In the sample data below, there are two such trips: C-D-C (2 stops).
and C-E-B-C (3 stops).
7. The number of trips starting at A and ending at C with exactly 4 stops.
In the sample data below, there are three such trips: A to C (via B,C,D); A
to C (via D,C,D); and A to C (via D,E,B).
8. The length of the shortest route (in terms of distance to travel) from A
to C.
9. The length of the shortest route (in terms of distance to travel) from B
to B.
10. The number of different routes from C to C with a distance of less than
30.  In the sample data, the trips are: CDC, CEBC, CEBCDC, CDCEBC,
CDEBC,CEBCEBC, CEBCEBCEBC.

Test Input:

For the test input, the planets are named using A to Z.  A route between two
planets (A to B) with a distance of 5 is represented as AB5.

Graph:
(Read from stdin,  fixed in code also acceptable. No need to validate.)
AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7


Expected Output:

Output #1: 9
Output #2: 5
Output #3: 13
Output #4: 22
Output #5: NO SUCH ROUTE
Output #6: 2
Output #7: 3
Output #8: 9
Output #9: 9
Output #10: 7
 
-----------------------------------------------------------------------------------------------------------
 
package cxg2;
import java.util.Map;
public interface ProblemState {
 public long processProblem(Map map);
 
}
---------------------------------------------------------------------------
 
package cxg2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Method1 {
 
 //存儲權重狀態
 private Map powerStateMap = new HashMap();
 //存儲顯示狀態
 private List viewStateList = new ArrayList();
 //某個狀態的輸出結果
 private long saveOutPut ;
 //用於輸出顯示
 private String printOutPut = null;
 
 public static void main(String[] args){
  Method1 instance = new Method1();
  instance.getInput();
  instance.processProblemState();
  instance.viewPrint();
 }
 
 /*
  * 從控制檯獲得輸入
  */
 private void getInput(){
  try {
         BufferedReader stdIn = new BufferedReader(
                 new InputStreamReader(System.in));
         String userInput;
         userInput = stdIn.readLine();
      System.out.println("Expected Output:");
      processInput(userInput);
       
      stdIn.close();
         }catch(IOException e){
          System.err.println("Couldn't get I/O .");
          System.exit(1);
         }
 }
 
 /*
  * 對輸入的字符串處理
  * 注意輸入時請去處空格
  */
 private void processInput(String input){
  String[] powers = input.split(",");
  for(int i=0;i<powers.length;i++){
   insertStateMap(powers[i]);
  }
 }
 
 /*
  * 對每個輸入的權重存入狀態Map中
  */
 private void insertStateMap(String power){
  //假設這裏輸入的都是不同的,AB5,BC4  存爲{ key:AB value:5 }
  String route = power.substring(0,2);
  String powerSize = power.substring(2);
  powerStateMap.put(route,powerSize);
 }
 
 /*
  * 利用反射機制可以減少代碼
  * 如果修改修改前5個state應該可以合併
  */
 private void processProblemState(){
  //1
  ProblemState state1 = new ConcreteProblemState1();
  saveOutPut = state1.processProblem(powerStateMap);
  viewStateList.add(String.valueOf(saveOutPut));
  
  //2
  ProblemState state2 = new ConcreteProblemState2();
  saveOutPut = state2.processProblem(powerStateMap);
  viewStateList.add(String.valueOf(saveOutPut));
  
  //3
  ProblemState state3 = new ConcreteProblemState3();
  saveOutPut = state3.processProblem(powerStateMap);
  viewStateList.add(String.valueOf(saveOutPut));
  
  //4
  ProblemState state4 = new ConcreteProblemState4();
  saveOutPut = state4.processProblem(powerStateMap);
  viewStateList.add(String.valueOf(saveOutPut));
  
  //5
  ProblemState state5 = new ConcreteProblemState5();
  saveOutPut = state5.processProblem(powerStateMap);
  viewStateList.add(String.valueOf(saveOutPut));
  
        //6
  ProblemState state6 = new ConcreteProblemState6();
  saveOutPut = state6.processProblem(powerStateMap);
  viewStateList.add(String.valueOf(saveOutPut));
  
        //7
  ProblemState state7 = new ConcreteProblemState7();
  saveOutPut = state7.processProblem(powerStateMap);
  viewStateList.add(String.valueOf(saveOutPut));
  
  //8
  ProblemState state8 = new ConcreteProblemState8();
  saveOutPut = state8.processProblem(powerStateMap);
  viewStateList.add(String.valueOf(saveOutPut));
  
  //9
  ProblemState state9 = new ConcreteProblemState9();
  saveOutPut = state9.processProblem(powerStateMap);
  viewStateList.add(String.valueOf(saveOutPut));
  
  //10
  ProblemState state10 = new ConcreteProblemState10();
  saveOutPut = state10.processProblem(powerStateMap);
  viewStateList.add(String.valueOf(saveOutPut));
  
 }
 
 /*
  * 顯示處理
  */
 private void viewPrint(){
  Iterator ite = viewStateList.iterator();
  int i = 0;
  while(ite.hasNext()){
   printOutPut = (String)ite.next();
   if(Long.parseLong(printOutPut) != 0){
    System.out.println("Output #"+ (++i) +": "+printOutPut);
   }else{
    System.out.println("Output #"+ (++i) +" NO SUCH ROUTE");
   }
  }
 }
 

 
}
----------------------------------------------------------------------------------------------
 
package cxg2;
import java.util.Iterator;
import java.util.Map;
public class Graph {
 //A:0 B:1 C:2 D:3 E:4
 private final int graphSize = 5;
 //通過數組簡便算法
 private int[][] graph = new int[graphSize][graphSize];
 
 private Map map = null;
 private void setMap(Map map) {
  this.map = map;
 }
 
 private String temp = null;
 private String begin = null;
 private String end = null;
 
 
 public int[][] createGraph(Map map){
  initGraph();
  setMap(map);
  Iterator ite = map.keySet().iterator();
  while(ite.hasNext()){
   temp = (String)ite.next();
   begin = temp.substring(0,1);
   end = temp.substring(1);
   int power = Integer.parseInt((String)map.get(temp));
   
   formGraph(begin,end,power);
  }
  
  return graph;
 }
 
 private void initGraph(){
  for(int i=0;i<graphSize;i++){
   for(int j=0;j<graphSize;j++){
    graph[i][j] = 0;
   }
  }
 }
 
 //集中處理所有的if,之前用集合對象處理stack out of memory,沒處理好
 private void formGraph(String begin,String end,int power){
  if(begin.equals(Constant.one)){
   if(end.equals(Constant.one)){
    graph[0][0] = power;
   }
   if(end.equals(Constant.two)){
    graph[0][1] = power;
   }
   if(end.equals(Constant.three)){
    graph[0][2] = power;
   }
   if(end.equals(Constant.four)){
    graph[0][3] = power;
   }
   if(end.equals(Constant.five)){
    graph[0][4] = power;
   }
  }//end one
  
  else if(begin.equals(Constant.two)){
   if(end.equals(Constant.one)){
    graph[1][0] = power;
   }
   if(end.equals(Constant.two)){
    graph[1][1] = power;
   }
   if(end.equals(Constant.three)){
    graph[1][2] = power;
   }
   if(end.equals(Constant.four)){
    graph[1][3] = power;
   }
   if(end.equals(Constant.five)){
    graph[1][4] = power;
   }
  }//end two
  
  else if(begin.equals(Constant.three)){
   if(end.equals(Constant.one)){
    graph[2][0] = power;
   }
   if(end.equals(Constant.two)){
    graph[2][1] = power;
   }
   if(end.equals(Constant.three)){
    graph[2][2] = power;
   }
   if(end.equals(Constant.four)){
    graph[2][3] = power;
   }
   if(end.equals(Constant.five)){
    graph[2][4] = power;
   }
  }//end three
  
  else if(begin.equals(Constant.four)){
   if(end.equals(Constant.one)){
    graph[3][0] = power;
   }
   if(end.equals(Constant.two)){
    graph[3][1] = power;
   }
   if(end.equals(Constant.three)){
    graph[3][2] = power;
   }
   if(end.equals(Constant.four)){
    graph[3][3] = power;
   }
   if(end.equals(Constant.five)){
    graph[3][4] = power;
   }
  }//end four
  
  else if(begin.equals(Constant.five)){
   if(end.equals(Constant.one)){
    graph[4][0] = power;
   }
   if(end.equals(Constant.two)){
    graph[4][1] = power;
   }
   if(end.equals(Constant.three)){
    graph[4][2] = power;
   }
   if(end.equals(Constant.four)){
    graph[4][3] = power;
   }
   if(end.equals(Constant.five)){
    graph[4][4] = power;
   }
  }//end five
 }
 
 /*
  * 用於獲取某個字符對應在數組中的標示
  */
 public int getStringToNum(String str){
  
  if(str.equals(Constant.one)){
   return 0;
  }else if(str.equals(Constant.two)){
   return 1;
  }else if(str.equals(Constant.three)){
   return 2;
  }else if(str.equals(Constant.four)){
   return 3;
  }else if(str.equals(str.equals(Constant.five))){
   return 4;
  }
  
  return -1;
 }
 
 
}
------------------------------------------------------------------------
package cxg2;
public class Constant {
 
 public static final String one = "A";
 public static final String two = "B";
 public static final String three = "C";
 public static final String four = "D";
 public static final String five = "E";
}
---------------------------------------------------------------------------------
package cxg2;
import java.util.Map;
public class ConcreteProblemState1 implements ProblemState{
 public long processProblem(Map map){
  //des:1. The distance of the route A-B-C.
        long distance = 0;
        String distance_one = "AB";
        String distance_two = "BC";
       
        String value_one = (String)map.get(distance_one);
        if(value_one != null && value_one.trim().length() >0){
         distance += Long.parseLong(value_one);
        }else return 0;
        String value_two = (String)map.get(distance_two);
        if(value_two != null && value_two.trim().length() >0){
         distance += Long.parseLong(value_two);
        }else return 0;
        return distance;
 }
 
}
-----------------------------------------------------------------------------------------------------
package cxg2;
import java.util.Map;
public class ConcreteProblemState2 implements ProblemState{
 public long processProblem(Map map){
  //des:1. The distance of the route  A-D.
        long distance = 0;
        String distance_one = "AD";
       
        String value_one = (String)map.get(distance_one);
        if(value_one != null && value_one.trim().length() >0){
         distance += Long.parseLong(value_one);
        }else return 0;
       
        return distance;
 }
 
}
----------------------------------------------------------------------------------------------
package cxg2;
import java.util.Map;
public class ConcreteProblemState3 implements ProblemState{
 public long processProblem(Map map){
  //des:1. The distance of the route A-D-C.
        long distance = 0;
        String distance_one = "AD";
        String distance_two = "DC";
       
        String value_one = (String)map.get(distance_one);
        if(value_one != null && value_one.trim().length() >0){
         distance += Long.parseLong(value_one);
        }else return 0;
        String value_two = (String)map.get(distance_two);
        if(value_two != null && value_two.trim().length() >0){
         distance += Long.parseLong(value_two);
        }else return 0;
        return distance;
 }
 
}
-----------------------------------------------------------------------------------------
package cxg2;
import java.util.Map;
public class ConcreteProblemState4 implements ProblemState{
 public long processProblem(Map map){
  //des:1. The distance of the route A-E-B-C-D.
        long distance = 0;
        String distance_one = "AE";
        String distance_two = "EB";
        String distance_three = "BC";
        String distance_four = "CD";
       
        String value_one = (String)map.get(distance_one);
        if(value_one != null && value_one.trim().length() >0){
         distance += Long.parseLong(value_one);
        }else return 0;
        String value_two = (String)map.get(distance_two);
        if(value_two != null && value_two.trim().length() >0){
         distance += Long.parseLong(value_two);
        }else return 0;
        String value_three = (String)map.get(distance_three);
        if(value_three != null && value_three.trim().length() >0){
         distance += Long.parseLong(value_three);
        }else return 0;
        String value_four = (String)map.get(distance_four);
        if(distance_four != null && distance_four.trim().length() >0){
         distance += Long.parseLong(value_four);
        }else return 0;
       
        return distance;
 }
 
}
---------------------------------------------------------------------------
package cxg2;
import java.util.Map;
public class ConcreteProblemState5 implements ProblemState{
 public long processProblem(Map map){
  //des:1. The distance of the route A-E-D.
        long distance = 0;
        String distance_one = "AE";
        String distance_two = "ED";
       
        String value_one = (String)map.get(distance_one);
        if(value_one != null && value_one.trim().length() >0){
         distance += Long.parseLong(value_one);
        }else return 0;
        String value_two = (String)map.get(distance_two);
        if(value_two != null && value_two.trim().length() >0){
         distance += Long.parseLong(value_two);
        }else return 0;
        return distance;
 }
 
}
-------------------------------------------------------------------------------------------
package cxg2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ConcreteProblemState6 implements ProblemState{
 
 private final String specialStr = "C";
 private int tripsNum = 0;
 private int[][] graphPower = null;
 private int controlTrips = 0;
 private int maxTrips = 3;
   
 public long processProblem(Map map){
  
  Graph graph = new Graph();
  graphPower = graph.createGraph(map);
  int len = graphPower.length;
  for(int i=0;i<len;i++){
   //now this do with special "C"
   int specialNum = graph.getStringToNum(specialStr);
   if (graphPower[specialNum][i] > 0){
    controlTrips = 0;
    if( test(i,specialNum,len) ){
     if(controlTrips > 3){
      continue;
     }else{
      tripsNum++;
     }
    }
   }
  }
  
  return tripsNum;
 }
 
 //
 private boolean test(int col,int specialNum,int len){
  //graphPower[specialNum,col]: fg. graphPower[2,1] = 4代表:CD=4 即CD4
  boolean flag = false;
  if(col == specialNum){
   return true;
  }else{
   for(int i=0;i<len;i++){
    if (graphPower[col][i] > 0){
     if(i == specialNum){
      return true;
     }else {
      flag = test(i,specialNum,len);
      if(flag){
       controlTrips++;
       //System.out.println("controlTrips = "+controlTrips);
      }
      return flag;
     }
    }
   }
   return false;
  }
  
 }
 
}
--------------------------------------------------------------------------
package cxg2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ConcreteProblemState7 implements ProblemState{
 
 private final String specialStr1 = "A";
 private final String specialStr2 = "C";
 private int tripsNum = 0;
 private int[][] graphPower = null;
 private int controlTrips = 0;
 private int maxTrips = 3;
 private Graph graph = new Graph();
   
 public long processProblem(Map map){
  
  //Graph graph = new Graph();
  graphPower = graph.createGraph(map);
  int len = graphPower.length;
  for(int i=0;i<len;i++){
   //now this do with special "C"
   int specialNum = graph.getStringToNum(specialStr1);
   if (graphPower[specialNum][i] > 0){//證明通路
    controlTrips = 0;
    if( test(i,specialNum,len) ){//這裏的specialNum是爲了兼容函數,沒有用
     if(controlTrips != 4){
      continue;
     }else{
      tripsNum++;
     }
    }
   }//否則此路不通
  }
  
  return tripsNum;
 }
 
 //
 private boolean test(int col,int specialNum,int len){
  boolean flag = false;
  specialNum = graph.getStringToNum(specialStr2);
  //graphPower[specialNum,col]: fg. graphPower[2,1] = 4代表:CD=4 即CD4
  if(col == specialNum && controlTrips ==4){
   return true;
  }else{
   for(int i=0;i<len;i++){
    if (graphPower[col][i] > 0){
     if(i == specialNum){
      if(controlTrips != 4){
       controlTrips++;
       flag = test(i,specialNum,len);
       if(!flag){
        controlTrips--;
       }
      }
      return true;
     }else {
      controlTrips++;
      flag = test(i,specialNum,len);
      if(!flag){
       controlTrips--;
       System.out.println("controlTrips = "+controlTrips);
      }
      return flag;
     }
    }
   }
   return false;
  }
  
 }
 
}
-----------------------------------------------------------------------------------
package cxg2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ConcreteProblemState8 implements ProblemState{
 
 private final String specialStr1 = "A";
 private final String specialStr2 = "C";
 private int tripsNum = 0;
 private int[][] graphPower = null;
 private int controlTrips = 0;
 private int maxTrips = 3;
 private Graph graph = new Graph();
 //最短路徑
 private int minToalPower = 0;
 //當前路徑和
 private int currentTotalPower =0;
   
 public long processProblem(Map map){
  
  //Graph graph = new Graph();
  graphPower = graph.createGraph(map);
  int len = graphPower.length;
  for(int i=0;i<len;i++){
   //now this do with special "C"
   int specialNum = graph.getStringToNum(specialStr1);
   if (graphPower[specialNum][i] > 0){//證明通路
    currentTotalPower += graphPower[specialNum][i];
    //controlTrips = 0;
    if( test(i,specialNum,len) ){//這裏的specialNum是爲了兼容函數,沒有用
     if(minToalPower == 0){
      minToalPower = currentTotalPower;
     }
     if(minToalPower > currentTotalPower){
      minToalPower = currentTotalPower;
     }
    }
   }//否則此路不通
  }
  
  return minToalPower;
 }
 
 //
 private boolean test(int col,int specialNum,int len){
  boolean flag = false;
  specialNum = graph.getStringToNum(specialStr2);
  //graphPower[specialNum,col]: fg. graphPower[2,1] = 4代表:CD=4 即CD4
  if(col == specialNum ){
   return true;
  }else{
   for(int i=0;i<len;i++){
    if (graphPower[col][i] > 0){
     if(i == specialNum){
      
      currentTotalPower += graphPower[col][i];
      return true;
      
     }else {
      currentTotalPower += graphPower[col][i];
      flag = test(i,specialNum,len);
      if(!flag){
       currentTotalPower -= graphPower[col][i];
       //System.out.println("controlTrips = "+controlTrips);
      }
      return flag;
     }
    }
   }
   return false;
  }
  
 }
 
}
--------------------------------------------------------------------------------
package cxg2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ConcreteProblemState9 implements ProblemState{
 
 private final String specialStr = "C";
 private int tripsNum = 0;
 private int[][] graphPower = null;
 private int controlTrips = 0;
 private int maxTrips = 3;
    //最短路徑
 private int minToalPower = 0;
 //當前路徑和
 private int currentTotalPower =0;
   
 public long processProblem(Map map){
  
  Graph graph = new Graph();
  graphPower = graph.createGraph(map);
  int len = graphPower.length;
  for(int i=0;i<len;i++){
   currentTotalPower = 0;
   //now this do with special "C"
   int specialNum = graph.getStringToNum(specialStr);
   if (graphPower[specialNum][i] > 0){//證明通路
    //controlTrips = 0;
    currentTotalPower += graphPower[specialNum][i];
    if( test(i,specialNum,len) ){
     if(minToalPower == 0){
      minToalPower = currentTotalPower;
     }
     if(minToalPower > currentTotalPower){
      minToalPower = currentTotalPower;
     }
    }
   }//否則此路不通
  }
  
  return minToalPower;
 }
 
 //
 private boolean test(int col,int specialNum,int len){
  //graphPower[specialNum,col]: fg. graphPower[2,1] = 4代表:CD=4 即CD4
  boolean flag = false;
  if(col == specialNum){
   return true;
  }else{
   for(int i=0;i<len;i++){
    if (graphPower[col][i] > 0){
     if(i == specialNum){
      currentTotalPower += graphPower[col][i];
      return true;
     }else {
      currentTotalPower += graphPower[col][i];
      flag = test(i,specialNum,len);
      if(!flag){
       currentTotalPower -= graphPower[col][i];
       //System.out.println("controlTrips = "+controlTrips);
      }
      return flag;
     }
    }
   }
   return false;
  }
  
 }
 
}
------------------------------------------------------------------------------------
package cxg2;
import java.util.HashMap;
import java.util.Map;
public class ConcreteProblemState10 implements ProblemState{
 
 private final String specialStr = "C";
 private int[][] graphPower = null;
 private int controlTrips = 0;
    //路徑上限
 private int maxToalPower = 30;
 //當前路徑和
// private int currentTotalPower =0;
 
 private Map routeMap = new HashMap();
 //private StringBuffer buffer = new StringBuffer();
   
 public long processProblem(Map map){
  
  Graph graph = new Graph();
  graphPower = graph.createGraph(map);
  int len = graphPower.length;
  for(int i=0;i<len;i++){
   //now this do with special "C"
   int specialNum = graph.getStringToNum(specialStr);
   if (graphPower[specialNum][i] > 0){//證明通路
    
    //buffer.append(specialNum).append(i);
    routeMap.put(String.valueOf(specialNum),"");
    
    test(specialNum+""+i,i,specialNum,len,graphPower[specialNum][i]) ;
    
   }//否則此路不通
  }
  
  return controlTrips;
 }
 
 //
 private boolean test(String route,int col,int specialNum,int len,int length){
  
  if(routeMap.containsKey(route)){
   return false;
  }
  routeMap.put(route,"");
  
  
  //graphPower[specialNum,col]: fg. graphPower[2,1] = 4代表:CD=4 即CD4
  boolean flag = false;
  
   for(int i=0;i<len;i++){
    if (graphPower[col][i] > 0){
     if(length + graphPower[col][i]< maxToalPower){
      if(i == specialNum){
       controlTrips++;
      }
      flag = test(route+i,i,specialNum,len,length+graphPower[col][i]);
      if(!flag){
       System.out.println("routeMap"+routeMap);
      }
      
     }
     
    }
   }
   return false;
  
 }
 
}
----------------------------------------------------------------------------------
 
以上程序已測試通過
 
 
 
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章