order pick-up and delivery problem

问题一:

pi表示取第i个单,di表示送第i个单。di不能在pi的前面。给一个取单送单的顺序,问是否是valid顺序。

 1 public boolean isValidOrderList(List list) {
 2         Set set = new HashSet<>();
 3         for (String item : list) {
 4             if (item.startsWith("P")) {
 5                 set.add(item);
 6             } else {
 7                 String parent = getParent(item);
 8                 if (!set.contains(parent)) {
 9                     return false;
10                 }
11                 set.remove(parent);
12             }
13         }
14         return set.isEmpty();
15     }
16     
17     
18     private String getParent(String dId) {
19         if (dId == null || dId.length() < 2 || dId.charAt(0) != 'D') {
20             throw new IllegalArgumentException("invalid input:" + dId);
21         }
22         
23         int id = Integer.parseInt(dId.substring(1));
24         return "P" + id;
25     }

问题二:

pi表示取第i个单,di表示送第i个单。di不能在pi的前面。给一个n,显示所有正确的顺序。

 1 public List> print(int n) {
 2         List> result = new ArrayList<>();
 3         List> tempList = new ArrayList<>();
 4         for (int j = 1; j <= n; j++) {
 5             if (j == 1) {
 6                 result.add(Arrays.asList("p1", "d1"));
 7                 continue;
 8             }
 9             for (int i = 0; i < result.size(); i++) {
10                 String[] temp = new String[j * 2];
11                 for (int p =  0; p < 2 * j; p++) {
12                     for (int q = p + 1; q < 2 * j; q++) {
13                         clearArray(temp);
14                         temp[p] = "p" + j;
15                         temp[q] = "d" + j;
16                         fillInArray(result.get(i), temp);
17                         tempList.add(arrayToList(temp));
18                     }
19                 }
20             }
21             result = new ArrayList<>(tempList);
22             tempList.clear();
23         }
24         
25         return result;
26     }
27     
28     private void clearArray(String[] arr) {
29         for (int i = 0; i < arr.length; i++) {
30             arr[i] = null;
31         }
32     }
33     
34     private void fillInArray(List result, String[] temp) {
35         int index = 0;
36         for (String str : result) {
37             while(temp[index] != null) {
38                 index++;
39             }
40             temp[index] = str;
41         }
42     }
43     
44     private List arrayToList(String[] arr) {
45         List list = new ArrayList<>();
46         for (String str : arr) {
47             list.add(str);
48         }
49         return list;
50     }

 

你可能感兴趣的:(order pick-up and delivery problem)