赞
踩
- #include<iostream>
- #include<algorithm>
- #include<queue>
- #define MAX 1000000
- #define MAXInt 31245
- using namespace std;
- typedef pair<int,int> Pair;//用优先队列选取权重最小的节点
- priority_queue<Pair,vector<Pair>,greater<Pair> >que;
- typedef struct ArcNode{
- int adjvex;
- int weight;
- struct ArcNode* nextarc;
- }ArcNode;
- typedef struct VNode{
- bool vis;
- int wei;
- ArcNode *firstarc;
- }VNode;
- typedef struct{
- VNode* vertice;
- int vexnum,arcnum;
- }ALGraph;
- void Creat(ALGraph &G){
- G.vertice=new VNode[MAX];
- for(int k=0;k<MAX;k++){
- G.vertice[k].firstarc=NULL;
- G.vertice[k].vis=false;
- G.vertice[k].wei=MAXInt;
- }
- for(int i=0;i<G.arcnum;i++){
- int v1,v2;
- cin>>v1>>v2;
- ArcNode *pe=new ArcNode;
- pe->adjvex=v2;
- pe->nextarc=G.vertice[v1].firstarc;
- G.vertice[v1].firstarc=pe;
- ArcNode *ep=new ArcNode;
- ep->adjvex=v1;
- ep->nextarc=G.vertice[v2].firstarc;
- G.vertice[v2].firstarc=ep;
- }
- }
- void Dij(ALGraph &G,int s){
- G.vertice[s].wei=0;
- que.push(Pair(0,s));
- while(!que.empty()){
- Pair tmp=que.top();
- que.pop();
- int v=tmp.second;//节点
- int w=tmp.first;//权重
- if(G.vertice[v].vis==true)
- continue;
- else
- G.vertice[v].vis=true;
- ArcNode *p=G.vertice[v].firstarc;
- while(p!=NULL){
- int v0=p->adjvex;
- if(w+1<G.vertice[v0].wei&&!G.vertice[v0].vis){
- G.vertice[v0].wei=G.vertice[v].wei+1;
- que.push(Pair(G.vertice[v0].wei,v0));
- }
- p=p->nextarc;
- }
- }
- }
- int main(){
- /*
- 11 0 8
- 0 1 6
- 0 2 4
- 0 3 5
- 1 4 1
- 2 4 1
- 3 5 2
- 4 6 9
- 4 7 7
- 5 7 4
- 6 8 2
- 7 8 4
- */
- ALGraph G;
- int s,e;
- cin>>G.arcnum>>s>>e;//输入边数,起点,终点
- Creat(G);
- Dij(G,s);
- if(G.vertice[e].wei!=MAXInt)
- cout<<G.vertice[e].wei<<endl;
- else
- cout<<-1<<endl;
- delete []G.vertice;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。