PAT-Java-1018-Public Bike Management (30)

1018. Public Bike Management (30)

题目阐述

There is a public bike service in Hangzhou City which provides great convenience to the tourists from all over the world. One may rent a bike at any station and return it to any other stations in the city.

The Public Bike Management Center (PBMC) keeps monitoring the real-time capacity of all the stations. A station is said to be in perfect condition if it is exactly half-full. If a station is full or empty, PBMC will collect or send bikes to adjust the condition of that station to perfect. And more, all the stations on the way will be adjusted as well.

When a problem station is reported, PBMC will always choose the shortest path to reach that station. If there are more than one shortest path, the one that requires the least number of bikes sent from PBMC will be chosen.

这里写图片描述

Figure 1 illustrates an example. The stations are represented by vertices and the roads correspond to the edges. The number on an edge is the time taken to reach one end station from another. The number written inside a vertex S is the current number of bikes stored at S. Given that the maximum capacity of each station is 10. To solve the problem at S3, we have 2 different shortest paths:

  1. PBMC -> S1 -> S3. In this case, 4 bikes must be sent from PBMC, because we can collect 1 bike from S1 and then take 5 bikes to S3, so that both stations will be in perfect conditions.

  2. PBMC -> S2 -> S3. This path requires the same time as path 1, but only 3 bikes sent from PBMC and hence is the one that will be chosen.

Input Specification:

Each input file contains one test case. For each case, the first line contains 4 numbers: Cmax (<= 100), always an even number, is the maximum capacity of each station; N (<= 500), the total number of stations; Sp, the index of the problem station (the stations are numbered from 1 to N, and PBMC is represented by the vertex 0); and M, the number of roads. The second line contains N non-negative numbers Ci (i=1,…N) where each Ci is the current number of bikes at Si respectively. Then M lines follow, each contains 3 numbers: Si, Sj, and Tij which describe the time Tij taken to move betwen stations Si and Sj. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print your results in one line. First output the number of bikes that PBMC must send. Then after one space, output the path in the format: 0->S1->…->Sp. Finally after another space, output the number of bikes that we must take back to PBMC after the condition of Sp is adjusted to perfect.

Note that if such a path is not unique, output the one that requires minimum number of bikes that we must take back to PBMC. The judge’s data guarantee that such a path is unique.

Sample Input:
10 3 3 5
6 7 0
0 1 1
0 2 1
0 3 3
1 3 1
2 3 1
Sample Output:
3 0->2->3 0


题目分析

这道题目初看非常复杂,而且是牛客网上的PAT甲级题目的第一道,第一次看到的时候还是觉得非常艰难的,不过理清了思路,做起来也没想象的那么难。关键是你得明白,题目需要你求什么?看需要输出的结果,第一是你出发时需要从PBMC拿走的单车数,第二是最短路径,第三是你遍历完后调整每个车站到完美状态后需要捎回来的车数目,而且最关键的是这些需要求算的关键信息中有满足的先后顺序,掌握这一点是最为关键的!题目按照一下顺序求解这些关键信息:

  • 先找到一条从PBMC出发到目标车站的最短路径
  • 如果路径有多条,那么选取从车站拿出的单车数量最少的那一条
  • 如果拿出的单车数量一样,那么选择调整完了最后捎回来的单车数量最少的那一条路径
  • 题目保证结果的唯一性。

如果你把这些信息都理清了,那么接下来就可以开始做题了。
需要注意几点:

  • 最短路径求解使用dijkstra算法,然后从起点到终点进行DFS遍历,中间记得加上剪枝,如路径超过最短路径即返回。
  • 深度遍历后一定记得恢复现场
  • 车辆的调整过程,一直保持两个变量,一个是沿着这条路径走下去从PBMC需要带来的车数目,一个是当前如果结束遍历我可以带回PBMC的车数量。
  • 车站数量是N,但是不包括PBMC,所以在存储图顶点时候必须多加1;

下面是我写的两个版本的代码,一开始觉的邻接表对于稀疏图非常实用,但是需要边的类实现以及让整个程序内存很大,于是写了第二个用邻接矩阵的实现,而且网上看到的许多demo和优秀回答都是采用邻接矩阵存储边的信息,况且题目里也强调了N数目不大于500,所以今后为了省空间还是直接采用数组实现比较方便点,而且代码写起来非常快!除非你想要追求速度,使用优先队列优化的话。

以下是代码:

  • 邻接表版本
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {

    static private int Cmax, N, des, total, send;
    static private int[] nums;
    static final private Main instance = new Main();
    static private List<Edge>[] adj;
    static private int[] dis;
    static private boolean[] marked;
    static private List<Integer> result = null;

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String[] temp1 = s.nextLine().trim().split(" ");
        Cmax = Integer.valueOf(temp1[0]);
        N = Integer.valueOf(temp1[1])+1;
        des = Integer.valueOf(temp1[2]);
        int m = Integer.valueOf(temp1[3]);

        nums = new int[N];
        adj = new ArrayList[N+1];
        for(int i=0; i<=N; i++)
            adj[i] = new ArrayList<>();
        dis = new int[N];
        for(int i=1; i<N; i++)
            dis[i] = Integer.MAX_VALUE;
        marked = new boolean[N];

        temp1 = s.nextLine().trim().split(" ");
        for(int i=1; i<N; i++)
            nums[i] = Integer.valueOf(temp1[i-1]);
        for(int i=0; i<m; i++) {
            temp1 = s.nextLine().trim().split(" ");
            int u = Integer.valueOf(temp1[0]);
            int v = Integer.valueOf(temp1[1]);
            int weigh = Integer.valueOf(temp1[2]);
            Edge e = instance.new Edge(u, v, weigh);
            adj[u].add(e);
            adj[v].add(e);

        }
        s.close();

        dijkstra(0);

        for(int i=0; i<marked.length; i++)
            marked[i] = false;
        marked[0] = true;
        List<Integer> temp = new ArrayList<>();
        temp.add(0);
        dfs(0, 0, 0, 0, temp);

        System.out.print(send + " ");
        for(int i=0; i<result.size(); i++) {
            if(i == 0) System.out.print(result.get(i));
            else System.out.print("->" + result.get(i));
        }
        System.out.print(" " + total);

    }

    private static void dfs(int u, int rout, int bag, int back, List<Integer> tempList) {
        if(rout > dis[des]) return;
        if(rout == dis[des] && u == des) {
            boolean flag = false;
            if(result == null) {
                flag = true;
            } else if(bag < send) {
                flag = true;
            } else if(bag == send && back < total) {
                flag = true;
            }
            if(flag) {
                result = new ArrayList<>(tempList);
                send = bag;
                total = back;
            } else return;
        } else if(rout == dis[des]) return;

        for(Edge e : adj[u]) {
            int b1 = bag, b2 = back;
            int v = e.other(u);
            if(marked[v]) continue;
            marked[v] = true;
            if(nums[v] < Cmax / 2) {
                int temp = Cmax / 2 - nums[v];
                if(back - temp >= 0) {
                    back -= temp;
                } else {
                    bag += (temp - back);
                    back = 0;
                }
            } else {
                int temp = nums[v] - Cmax / 2;
                back += temp;
            }
            tempList.add(v);
            dfs(v, rout + e.weigh, depth + 1, bag, back, tempList);
            bag = b1;
            back = b2;
            marked[v] = false;
            tempList.remove(tempList.size()-1);
        }

    }

    private static void dijkstra(int s) {
        dis[s] = 0;
        int min, u;
        while(true) {
            min = Integer.MAX_VALUE;
            u = -1;
            for(int i=0; i<N; i++)
                if(!marked[i] && dis[i] < min) {
                    min = dis[i];
                    u = i;
                }
            if(u == -1) break;
            marked[u] = true;
            for(Edge e : adj[u]) {
                int v = e.other(u);
                if(dis[u] + e.weigh < 0) continue;
                if(dis[v] > dis[u] + e.weigh)
                    dis[v] = dis[u] + e.weigh;
            }
        }
    }

    private class Edge {
        private int u, v, weigh;
        Edge(int u, int v, int weigh) {
            this.u = u;
            this.v = v;
            this.weigh = weigh;
        }

        public int other(int k) {
            if(k == u) return v;
            return u;
        }

    }


}
  • 邻接矩阵版本
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

  static int Cmax, N, des, total, send; //每个车站最大容量(偶数),车站数,目标地点,需从PBMC带走的车数目,需要捎回来的车数目
  static int[] nums, dis; //最短路径数组
  static int[][] edges; //邻接矩阵
  static boolean[] marked; // 记录布尔值
  static private List<Integer> result = null; // result用来记录深搜过程中遍历经过的顶点

  public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    Cmax = s.nextInt();
    N = s.nextInt() + 1;
    des = s.nextInt();
    int M = s.nextInt();
    nums = new int[N];
    dis = new int[N];
    for(int i=0; i<N; i++)
      dis[i] = Integer.MAX_VALUE;
    marked = new boolean[N];
    edges = new int[N][N];
    for(int i=0; i<N; i++) 
      for(int j=0; j<N; j++) 
        if(j == i) edges[i][j] = 0;
        else edges[i][j] = Integer.MAX_VALUE;
    for(int i=1; i<N; i++)
      nums[i] = s.nextInt();
    for(int i=0; i<M; i++) {
      int u = s.nextInt();
      int v = s.nextInt();
      edges[u][v] = s.nextInt();
      edges[v][u] = edges[u][v];
    }
    s.close();

    dis[0] = 0;
    dijkstra();

    for(int i=0; i<marked.length; i++)
      marked[i] = false;
    marked[0] = true;
    List<Integer> temp = new ArrayList<>();
    temp.add(0);
    dfs(0, 0, 0, 0, temp);

    System.out.print(send + " ");
    for(int i=0; i<result.size(); i++) {
      if(i == 0) System.out.print(result.get(i));
      else System.out.print("->" + result.get(i));
    }
    System.out.print(" " + total);  

  }

  private static void dfs(int u, int rout, int bag, int back, List<Integer> tempList) {
    if(rout > dis[des]) return; // 剪枝的过程
    if(rout == dis[des] && u == des) {
      boolean flag = false;
      if(result == null) {
        flag = true;
      } else if(bag < send) {
        flag = true;
      } else if(bag == send && back < total) {
        flag = true;
      }
      if(flag) {
        result = new ArrayList<>(tempList); //这一句很重要哦!
                send = bag;
                total = back;
      } else return;
    } else if(rout == dis[des]) return;

    for(int i=0; i<N; i++) {
      if(edges[u][i] == Integer.MAX_VALUE) continue; // 不加这一句,存在越界的可能,因为Edges[u][i]可能是无穷大,和rout相加更加越界,所以这种情况就不许要继续深搜了。
      int b1 = bag, b2 = back; // 保留现场!
      if(marked[i] || dis[i] == Integer.MAX_VALUE) continue;
      marked[i] = true;
      if(nums[i] < Cmax / 2) {
        int temp = Cmax / 2 - nums[i];
        if(back - temp >= 0) {
          back -= temp;
        } else {
          bag += (temp - back);
          back = 0;
        }
      } else {
        int temp = nums[i] - Cmax / 2;
        back += temp;
      }
      tempList.add(i);

      dfs(i, rout + edges[u][i], bag, back, tempList);

      bag = b1;
      back = b2;
      marked[i] = false; // 恢复现场
      tempList.remove(tempList.size()-1);
    }

  }

/**
* 求算最短路径的方法
*/
  private static void dijkstra() {
    int min, u;
    for(int i=0; i<N; i++) {
      u = -1;
      min = Integer.MAX_VALUE;
      for(int j=0; j<N; j++) {
        if(!marked[j] && dis[j] < min) {
          min = dis[j];
          u = j;
        }
      }
      if(u == -1) break;
      marked[u] = true;
      for(int j=0; j<N; j++) {
        if(dis[u] + edges[u][j] < 0) continue; //防止和越界
        if(dis[j] > dis[u] + edges[u][j])
          dis[j] = dis[u] + edges[u][j];
      }
    }
  }
}

两次都完美运行,但是感觉内存还是有点大,时间也不够快。

总结

图的算法总体上都是在基于最短路径算法和深搜算法基础上再增加一点点难度,这一点点体现在比如这道题上的车辆数的求算,其实本身并不难,只不过加上之前一大堆的图创建,最短路径的求算,和深搜过程的信息求算和保存,比较,显得有点冗杂。其实剪枝过程还可以不断优化,比如每dfs到一个顶点mid,只要此时的rout已经超过了此刻的dis[mid],那么就立刻返回,这个mid不一定必须的最终的des,可能是中间的任意一个顶点,为什么?因为从出发点到des的最短路径中经过的任意一个顶点到出发点都是最短路径才行,如果此时超过,那么走下去必然超过最短路径,所以就没有继续搜索的必要了。而我以上的代码,还没有做到这样的优化,而且,我相信诸如此类的优化还有不少。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值