找了不少帖子,发现大家的思路都很好,但对于我这个AcWing的小白来说还是有点难以理解,这里把自己琢磨的AC代码分享出来,学了AcWing算法基础课的朋友应该可以看的更轻松。
//朴素版本
#include<bits/stdc++.h>
using namespace std;
const int N = 2010;
const int M = 1e5+10;
int e[M],ne[M],h[N],idx;
double w[M];
int n,m,A,B;
int state[N];
double dist[N];
void add(int k,int x,double y)
{
e[idx] = x, w[idx] = 1-y*0.01, ne[idx] = h[k], h[k] = idx++;
}
void diji()
{
fill(dist,dist+1+N,0);
dist[A] = 1;
for(int i = 1;i <=n;i++)
{
int t = -1;
for(int j = 1;j <=n;j++)
{
if(!state[j] && (t == -1 || dist[j] > dist[t]))
t = j;
}
//cout << t<<endl;
if(t == -1)return;
state[t] = 1;
for(int k = h[t];k != -1;k = ne[k])
{
int j = e[k];
dist[j] = max(dist[j],dist[t]*w[k]);
// cout << t<<endl;
}
}
}
int main()
{
memset(h,-1,sizeof h);
cin >> n >> m;
while(m--)
{
int a,b;
double c;
cin >> a >> b >> c;
add(a,b,c);
add(b,a,c);
}
cin >> A >> B;
if(A>B)swap(A,B);
diji();
// cout << dist[n] << endl;
//for(int i = 1;i<=n;i++)cout <<fixed<<setprecision(8)<< w[i]<<endl;
//cout << dist[B] << endl;
cout <<fixed<<setprecision(8)<< 100/dist[B];
}
//堆优化版本
#include<bits/stdc++.h>
using namespace std;
const int N = 2010;
const int M = 2e5+10;
int e[M],ne[M],h[N],idx;
int state[N];
double dist[N],w[M];
int n,m,A,B;
typedef pair<double,int> PII;
priority_queue <PII> heap;//distance,ver
void add(int k,int x,double y)
{
e[idx] = x, w[idx] = 1-y*0.01, ne[idx] = h[k], h[k] = idx++;
}
void diji()
{
fill(dist,dist+1+N,0);
dist[A] = 1;
heap.push({1,A});
while(heap.size())
{
PII t = heap.top();
heap.pop();
int ver = t.second;
if(state[ver]) continue;
else state[ver] = 1;
for(int i = h[ver]; i != -1;i = ne[i])
{
int j = e[i];
if(dist[j] < dist[ver]*w[i])
{
dist[j] = dist[ver]*w[i];
heap.push({dist[j],j});
}
}
}
}
int main()
{
memset(h,-1,sizeof h);
cin >> n >> m;
while(m--)
{
int a,b;
double c;
cin >> a >> b >> c;
add(a,b,c);
add(b,a,c);
}
cin >> A >> B;
if(A>B)swap(A,B);
diji();
//for(int i = 1;i<=n;i++)cout <<fixed<<setprecision(8)<< w[i]<<endl;
//cout << dist[B] << endl;
cout <<fixed<<setprecision(8)<< 100/dist[B];
return 0;
}