不解释,这里只是分享代码,练练堆
#include<stdio.h>
#include<iostream>
#include<memory.h>
#include<vector>
#include<queue>
using namespace std;
const int MAX_N = 1001;
const int INF =1<<30;
struct nodelink
{
int s,t,w;
}pnod;
vector<struct nodelink> G1[MAX_N],G2[MAX_N];
struct node
{
int ID;
int dv;
}head;
priority_queue<struct node> Q1,Q2;
int S1[MAX_N];
int S2[MAX_N];
bool operator<(struct node a,struct node b)
{
return a.dv>b.dv;
}
bool have1[MAX_N];
bool have2[MAX_N];
int ans;
int N,M,X;
void init()
{
scanf("%d %d %d",&N,&M,&X);
int i;
int x,y,w;
for(i=1;i<=M;i++)
{
scanf("%d %d %d",&x,&y,&w);
pnod.s=x;
pnod.t=y;
pnod.w=w;
G1[x].push_back(pnod);
pnod.s=y;
pnod.t=x;
pnod.w=w;
G2[y].push_back(pnod);
}
}
void DijkStra1()
{
int i,j,k;
memset(have1,true,sizeof(have1));
for (i=1;i<=N;i++)
S1[i]=INF;
S1[X]=0;
for (i=1;i<=N;i++)
{
head.ID=i;
head.dv=S1[i];
Q1.push(head);
}
int tmp = 0;
while (!Q1.empty())
{
int s=Q1.top().ID;
Q1.pop();
if(have1[s])
{
have1[s]=true;
tmp++;
vector <struct nodelink> ::iterator iter;
for (iter=G1[s].begin();iter!=G1[s].end();iter++)
{
if (have1[iter->t]&&S1[s]+iter->w<S1[iter->t])
{
S1[iter->t] = S1[s]+iter->w;
head.ID=iter->t;
head.dv=S1[iter->t];
Q1.push(head);
}
}
}
}
}
void DijkStra2()
{
int i,j,k;
memset(have2,true,sizeof(have2));
for (i=1;i<=N;i++)
S2[i]=INF;
S2[X]=0;
for (i=1;i<=N;i++)
{
head.ID=i;
head.dv=S2[i];
Q2.push(head);
}
int tmp = 0;
while (!Q2.empty())
{
int s=Q2.top().ID;
Q2.pop();
if(have2[s])
{
have2[s]=true;
tmp++;
vector <struct nodelink> ::iterator iter;
for (iter=G2[s].begin();iter!=G2[s].end();iter++)
{
if (have2[iter->t]&&S2[s]+iter->w<S2[iter->t])
{
S2[iter->t] = S2[s]+iter->w;
head.ID=iter->t;
head.dv=S2[iter->t];
Q2.push(head);
}
}
}
}
}
void put()
{
int ans = 0;
int i;
for(i=1;i<=N;i++)
ans=max(ans,S1[i]+S2[i]);
printf("%d",ans);
}
int main()
{
freopen("party.in","r",stdin);
freopen("party.out","w",stdout);
init();
DijkStra1();
DijkStra2();
put();
return 0;
}