大数据量处理dijkstra
#include <iostream>
#include <fstream>
#include <hash_map>
#include <string>
#include <stdlib.h>
#include <queue>
using namespace std;
using namespace stdext;
struct DisNode{
int node;
double cost;
DisNode *next;
};
struct OriNode{
int node;
int edgeNum;
DisNode *first;
};
double INFINIT = 99999999;
int NODE_NUM;
int main()
{
cout<<"test begin"<<endl;
const char* AListFile = "AdjacencyList.txt";
const char* LCostFile = "LinkCost.txt";
const int MIN = 800000000;
NODE_NUM = 0;
hash_map<int,double> LCostHash;
hash_map<int,OriNode*> NodeHash;
ifstream if_AList;
ifstream if_LCost;
if_AList.open(AListFile);
if_LCost.open(LCostFile);
if(if_AList.is_open()&&if_LCost.is_open())
{
cout<<"file is opened"<<endl;
int Lid = 0;
double cost = 0.000;
char line[30];
//save cost
while(!if_LCost.eof())
{
if_LCost.getline(line,30);
char* str = strstr(line,",");
// cout<<str<<endl;
int size = str - line;
char LidC[10];
strncpy(LidC,line,size);
LidC[size] = '/0';
char*CostC = str +1;
Lid = atoi(LidC);
cost = atof(CostC);
cout<<Lid<<" "<<cost<<endl;
LCostHash[Lid] = cost;
}
//save cost
cout<<"hashtable is saved"<<endl;
//save node info
while(!if_AList.eof())
{
NODE_NUM ++;
int node;
int edgeNum;
OriNode* orinode = (OriNode *)malloc(sizeof(OriNode));
if_AList>>node;
if_AList>>edgeNum;
orinode->node = node;
orinode->edgeNum = edgeNum;
DisNode *disnodeTemp = (DisNode *)malloc(sizeof(DisNode)) ;
int dis_node;
if_AList>>dis_node;
disnodeTemp->node = dis_node;
int cid;
if_AList>>cid;
disnodeTemp->cost = LCostHash[cid];
orinode->first = disnodeTemp;
cout <<orinode->node<<" "<<orinode->edgeNum<<" ";
for (int j = 1; j < orinode->edgeNum; j++)
{
DisNode *disnode = (DisNode *)malloc(sizeof(DisNode));
if_AList>>disnode->node;
cout <<disnode->node<<" ";
int cid;
if_AList>>cid;
disnode->cost = LCostHash[cid];
disnodeTemp->next = disnode;
disnodeTemp = disnode;
}
NodeHash[orinode->node] = orinode;
cout<<endl;
}
//save node info
//测试保存结果
cout<<LCostHash[2]<<endl;
cout<<((OriNode*)NodeHash[3])->node<<endl;
//测试保存结果
if_AList.close();
if_LCost.close();
}
//dijkstra
int oriID;
int desID;
cout<<"Please enter the original node id: ";
cin>>oriID;
cout<<endl;
cout<<"Please enter the destination node id: ";
cin>>desID;
cout<<endl;
cout<<"wait..."<<endl;
queue<int> QNode;
hash_map<int,double> QCostHash;
for (int n = 0; n < 1000; n++)
{
QCostHash[n] = INFINIT;
}
QCostHash[oriID] = 0;
QNode.push(oriID);
while(!QNode.empty())
{
int uNode = QNode.front();
QNode.pop();
if(uNode == desID)
{
break;
}
OriNode * uOriNode = (OriNode*)NodeHash[uNode];
DisNode* uDisNode = uOriNode->first;
for (int m = 0; m < uOriNode->edgeNum; m++)
{
int alt = QCostHash[uNode] + uDisNode->cost;
if(alt < QCostHash[uDisNode->node])
{
QCostHash[uDisNode->node] = alt;
}
QNode.push(uDisNode->node);
uDisNode = uDisNode->next;
}
}
cout<<"The result is :"<<QCostHash[desID]<<endl;
//dijkstra
int test;
cin>>test;
return 0;
}