做法:Dijkstran因为本题数据过大,所以需要邻接表+堆优化本题所用时间取决于:最后一名同学拿到糖果的时间+他本身吃糖果需要的时间所以,本题做法显而易见1.先求出到所有同学的最短路径2.求出所有最短路径中最长的路径所对应的点
代码
邻接表+STL堆优化
C++#include<iostream>
#include<queue>
using namespace std;
#define MAXN 101
#define INF 0x3f3f3f3f
struct Edge
{
int to;
int w;
int next;
} edge[MAXN*MAXN];
struct Node
{
int no;
int d;
bool operator<(const Node x)const{
return d>x.d;
}
// Node(int a,int b)
// {
// no=a;d=b;
// }
// Node(){
// }
};
priority_queue<Node> hp;
int n,m,start,head[MAXN],vis[MAXN]={0},d[100],cnt=0,path[MAXN];
void add_edge(int from,int to,int w)
{
cnt++;
edge[cnt].next=head[from];
head[from]=cnt;
edge[cnt].to=to;
edge[cnt].w=w;
}
void dijkstr(int s)
{
for(int i=1;i<=n;i++) d[i]=INF;
d[s]=0;
Node x;
x.d=0;
x.no=s;
hp.push(x);
while(hp.size())
{
Node t=hp.top();
hp.pop();
int u=t.no;
if(vis[u]) continue;
vis[u]=true;
for(int i=head[u];i;i=edge[i].next){
int v=edge[i].to;
if(d[v]>d[u]+edge[i].w){
d[v]=d[u]+edge[i].w;
path[v]=u;
Node y;
y.no=v;
y.d=d[v];
hp.push(y);
}
}
}
}
void dfs(int i)
{
if(i!=start) dfs(path[i]);
cout<<i<<' ';
}
void print()
{
for (int i=1;i<=n;i++)
if(i!=start)
{
dfs(i);
cout<<d[i]<<endl;
}
}
int main()
{
cin>>n>>m>>start;
for(int i=1;i<=m;i++)
{
int x,y,z;
cin>>x>>y>>z;
add_edge(x,y,z);
add_edge(y,x,z);
}
dijkstr(start);
print();
return 0;
}```