您的位置:首页 > 其它

PAT-1030 Travel Plan (30)

2018-02-28 16:36 423 查看
题目大意:在确保最短路径下输出费用最小的路径、最短路径数值和花费。
解题思路:和 1003.Emergency 一样的解法,改进下 Dijkstra 算法即可。
题目链接:https://www.patest.cn/contests/pat-a-practise/1030#include <iostream>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
const int MAXSIZE = 505;
const int INF = 1<<30;

typedef struct GMap{
int cost,dis;
}GMap;

GMap gMap[MAXSIZE][MAXSIZE];
bool visited[MAXSIZE];
int lowcost[MAXSIZE];
int costMin[MAXSIZE];
int path[MAXSIZE];
int n,m,s,d;

void init()
{
fill(visited,visited+MAXSIZE,false);
fill(lowcost,lowcost+MAXSIZE,INF);
fill(costMin,costMin+MAXSIZE,INF);
fill(path,path+MAXSIZE,-1);
for(int i=0;i<MAXSIZE;++i)
for(int j=0;j<MAXSIZE;++j)
{
gMap[i][j].cost = INF;
gMap[i][j].dis = INF;
}
}

void Dijk(int s)
{
int u;
visited[s] = true;
u = s;
path[u] = -1;
for(int i=0;i<n;++i)
{
if(gMap[u][i].dis != INF)
{
lowcost[i] = gMap[u][i].dis;
costMin[i] = gMap[u][i].cost;
path[i] = u;
}
}
for(int i=0;i<n-1;++i)
{
int Min = INF,pos;
for(int j=0;j<n;++j)
{
if(lowcost[j]<Min && visited[j]==false)
{
Min = lowcost[j];
pos = j;
}
}
u = pos;
visited[u] = true;
for(int j=0;j<n;++j)
{
if(visited[j]==false && lowcost[u]+gMap[u][j].dis<lowcost[j])
{
lowcost[j] = lowcost[u]+gMap[u][j].dis;
if(lowcost[j] == 1)
cout << lowcost[u] <<" " << gMap[u][j].dis <<endl;
path[j] = u;
costMin[j] = costMin[u]+gMap[u][j].cost;
}
//改进的地方
else if(visited[j]==false && lowcost[u]+gMap[u][j].dis==lowcost[j])
{
if(costMin[j] > costMin[u]+gMap[u][j].cost)
{
path[j] = u;
costMin[j] = costMin[u]+gMap[u][j].cost;
}
}
}
}
}

void printPath(int d)
{
if(path[d] == -1)
{
cout << d << " ";
return;
}
printPath(path[d]);
cout << d <<" ";
}

int main(int argc, char** argv) {
cin >> n >> m >> s >> d;
init();
for(int i=0;i<m;++i)
{
int c1,c2,dis,cost;
cin >> c1 >> c2 >> dis >> cost;
gMap[c1][c2].dis = dis;
gMap[c2][c1].cost = cost;
gMap[c2][c1].dis = dis;
gMap[c1][c2].cost = cost;
}
Dijk(s);
printPath(d);
//
// for(int i=0;i<n;++i)
// cout<< path[i] <<endl;
// cout<<endl;
cout<< lowcost[d] << " " << costMin[d] << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: