PAT 1018 Public Bike Management
2018-05-08 本文已影响0人
烤肉拌饭多加饭
题目理解错了就很难受。
送回中心(back>=0)和送出中心(need<=0)两个都要计算
按下图理解
need=2,back=3
按我写的那就是back=1;need=0。
这样对于权重为0的那个点,上面给他3,目标节点p(权重w=8)给它2,然后返回center 1个。也就是对于目标节点p实际上有两个操作,送出和送回;题意应该是目标节点p只有一个操作的(送出或者送回)。
看到还有一个解释:实际测试是只能在去往目的地的途中调整,回来的途上不可调整。
然后改了代码如下:
/*1018 Public Bike Management*/
#include<iostream>
#include<climits>
#include<vector>
#include<iterator>
using namespace std;
const int N = 510;
int c,n,p, e;//最大容量c,停车点数量n,有问题停车点下标p,路的数量
int perfect;
int *Cap;//现在停车点i的车数
int num[N] = { 0 };//记录到i有几条最短路径
int **G;//停车点图
vector<int> pre[N];//节点i的前驱节点数组
vector<int> Path, tmpPath;
int *d = new int[N];
int MinNeed = N*100,MinBack=N*100;
void Dijkstra() {
int stationN = n + 1;
int *visit = new int[stationN];
for (int i = 0; i < stationN; i++) {
d[i] = INT_MAX;
visit[i] = 0;
}
d[0] = 0;//0永远是起始点
num[0] = 1;//其余路径数还是0
int control = 0;
while (control < stationN) {
int u = -1;
int min = INT_MAX;
//找到未访问过且d[u]最小的顶点
for (int i = 0; i < n; i++) {
if (!visit[i] && d[i] < min) {
min = d[i];
u = i;
}
}
if(u == -1)return;
visit[u] = 1;//标记访问过
for (int j = 0; j < stationN; j++) {//从u出发
if (G[u][j] != 0 && !visit[j]) {//有路
if ( d[j] > d[u] + G[u][j]) {
num[j] = num[u];
d[j] = d[u] + G[u][j];
pre[j].clear();
pre[j].push_back(u);
}
else if (d[j] == d[u] + G[u][j]) {
pre[j].push_back(u);
num[j] = num[j] + num[u];
}
}
}
control++;
}
}
void DFS(int v) {//DFS输出minBikes最小的路线
if (v == 0) {//到达中心站
int need = 0,back=0;
tmpPath.push_back(v);
//比较
int sizeNum = tmpPath.size();//center下标为u=sizeNum-1,tmpPath[u]=0;
for (int i=sizeNum-2;i>=0; i--) {
int tmp= Cap[tmpPath[i]] - perfect;//>0送回,<0 need
if (tmp > 0) {//i要送出去tmp辆车
back += tmp;
}
else {
//tmp<0,i需要-tmp辆车
if (back > abs(tmp)) {
back += tmp;
}
else {
need = need + abs(tmp)-back;
back = 0;
}
}
}
if (MinNeed > need) {
MinNeed = need;
MinBack = back;
Path.clear();
for (int i = 0; i < tmpPath.size(); i++) {
Path.push_back(tmpPath[i]);
}
}
else if (MinNeed == need && MinBack > back) {
MinBack = back;
Path.clear();
for (int i = 0; i < tmpPath.size(); i++) {
Path.push_back(tmpPath[i]);
}
}
tmpPath.pop_back();
return;
}
else {
tmpPath.push_back(v);
for (int i = 0; i <pre[v].size(); i++) {
DFS(pre[v][i]);
}
tmpPath.pop_back();
}
}
int main()
{
cin >> c >> n>> p >> e;
perfect = c / 2;
G = (int **)new int*[n+1];//0 center n parking dot
for (int i = 0; i < n+1; i++) {//初始化图G,有n个城市(顶点)
G[i] = new int[n+1];
for (int j = 0; j < n+1; j++) {
G[i][j] = 0;//表示没路
}
}
Cap = new int[n+1];
Cap[0] = 0;
for (int i = 1; i < n + 1; i++) {
cin >> Cap[i];
}
int x, y, t;
for (int i = 0; i < e; i++) {//初始化路径和消耗权重
cin >> x >> y >> t;
G[x][y] = t;
G[y][x] = t;
}
Dijkstra();
DFS(p);
cout << MinNeed << " "<<0;
for (int i = Path.size()-2; i>=0; i--) {
cout << "->" << Path[i];
}
cout <<" "<<MinBack;
return 0;
}