1 Star 0 Fork 0

hsmath/PAT advanced

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
1030.cpp 2.35 KB
一键复制 编辑 原始数据 按行查看 历史
hsmath 提交于 2021-07-25 02:50 . 1030
/**
* @file 1030.cpp
* @author Shuang Hu <hsmath@ubuntu>
* @date Sun Jul 25 01:43:35 2021
*
* @brief PAT advanced 1030
*
*
*/
#include<iostream>
#include<vector>
#include<map>
using namespace std;
#define Infinity 0xffffff;
class roadinfo{
public:
int dist;
int cost;
};
bool cmp(roadinfo& R1,roadinfo& R2){
if(R1.dist<R2.dist){
return true;
}else if(R1.dist==R2.dist){
if(R1.cost<R2.cost){
return true;
}
}
return false;
}
roadinfo add(roadinfo& R1,roadinfo& R2){
roadinfo I;
I.dist=R1.dist+R2.dist;
I.cost=R1.cost+R2.cost;
return I;
}
class Map{
private:
vector<vector<roadinfo>> AdjMat;//Using adjacency matrix to store the road information.
int Nv;
int Ne;
int from;
int to;
vector<roadinfo> distinf;
vector<bool> known;
map<int,int> path;
public:
Map();//Build a graph!
void dijkstra();//Dijkstra Algorithm!
void print();
};
Map::Map(){
cin>>Nv>>Ne>>from>>to;
AdjMat.resize(Nv);
roadinfo I;
I.dist=-1;
I.cost=0;
for(int i=0;i<Nv;i++){
for(int j=0;j<Nv;j++){
AdjMat[i].push_back(I);//Initialize!
}
}
for(int i=0;i<Ne;i++){
roadinfo J;
int a,b;
cin>>a>>b>>J.dist>>J.cost;
AdjMat[a][b]=J;
}
I.dist=Infinity;
I.cost=0;
for(int i=0;i<Nv;i++){
distinf.push_back(I);
known.push_back(false);
}
}
void Map::dijkstra(){
distinf[from].dist=0;
distinf[from].cost=0;
while(1){
int index=0;
bool quit=true;
for(int i=0;i<Nv;i++){
if(known[i]==false){
index=i;
quit=false;
break;
}
}
if(quit==true){
break;
}
for(int i=0;i<Nv;i++){
if(known[i]==false){
if(cmp(distinf[i],distinf[index])){
index=i;
}
}
}
known[index]=true;
for(int i=0;i<Nv;i++){
if(AdjMat[index][i].dist!=-1){//Adjacent to such index
if(known[i]==false){
roadinfo R=add(AdjMat[index][i],distinf[index]);
if(cmp(R,distinf[i])){
distinf[i]=R;
path[i]=index;
}
}
}
}
}
}
void Map::print(){
vector<int> nowpath;
int nowpos=to;
nowpath.push_back(nowpos);
while(nowpos!=from){
nowpos=path[nowpos];
nowpath.push_back(nowpos);
}
cout<<nowpath[nowpath.size()-1];
for(int i=nowpath.size()-2;i>=0;i--){
cout<<" "<<nowpath[i];
}
cout<<" "<<distinf[to].dist<<" "<<distinf[to].cost<<endl;
}
int main(){
Map M;
M.dijkstra();
M.print();
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/hsmath/pat-advanced.git
git@gitee.com:hsmath/pat-advanced.git
hsmath
pat-advanced
PAT advanced
master

搜索帮助