题目链接:
https://www.luogu.org/problem/P3003
思路:
1:最短路水题,dijkstra AC
2:spfa 10个测试点过8个,2个TLE
代码:
1:dijkstra AC
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+1;
vector<pair<int,int> >e[maxn];
int n,m,s,t,p,d[maxn],a,b,c,temp,sum;
inline void dijkstra(int s)
{
memset(d,0x7f,sizeof(d));
priority_queue<pair<int,int> >q;
q.push(make_pair(-d[s],s));
d[s]=0;
while(!q.empty())
{
int now=q.top().second;
q.pop();
for(int i=0;i<e[now].size();i++)
{
int v=e[now][i].first;
if(d[v]>d[now]+e[now][i].second)
{
d[v]=d[now]+e[now][i].second;
q.push(make_pair(-d[v],v));
}
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin>>m>>n>>s>>t>>p;
for(int i=1;i<=m;i++)
{
cin>>a>>b>>c;
e[a].push_back(make_pair(b,c));
e[b].push_back(make_pair(a,c));
}
dijkstra(s);
temp=min(d[t],d[p]);
dijkstra(t);
sum=temp+d[p];
cout<<sum<<endl;
return 0;
}
2:spfa 过8个,2个TLE
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+1;
vector<pair<int,int> >e[maxn];
int n,m,s,t,p,d[maxn],ing[maxn],a,b,c,temp,sum;
inline void spfa(int s)
{
memset(ing,0,sizeof(ing));
memset(d,0x7f,sizeof(d));
queue<int>q;
q.push(s);
d[s]=0;
ing[s]=1;
while(!q.empty())
{
int now=q.front();
q.pop();
ing[now]=0;
for(int i=0;i<e[now].size();i++)
{
int v=e[now][i].first;
if(d[v]>d[now]+e[now][i].second)
{
d[v]=d[now]+e[now][i].second;
if(ing[v])
continue;
q.push(v);
ing[v]=1;
}
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin>>m>>n>>s>>t>>p;
for(int i=1;i<=m;i++)
{
cin>>a>>b>>c;
e[a].push_back(make_pair(b,c));
e[b].push_back(make_pair(a,c));
}
spfa(s);
temp=min(d[t],d[p]);
spfa(t);
sum=temp+d[p];
cout<<sum<<endl;
return 0;
}