这题是稍微拓展了的一道最短路的题目
首先对数有一些基本的性质: log ( a ∗ b ) = l o g a + l o g b \log(a*b)=loga+logb log(a∗b)=loga+logb
然后在跑最短路的时候记录一下前驱,最后求答案的时候算一下就好了
代码如下:
#include <cstdio>
#include <cmath>
#include <queue>
#define maxn 2000 + 10
#define maxm 2000000 + 10
#define inf 2147483647
#define mod 9987
using namespace std;
const int s = 1;
int n, m, cnt;
int vis[maxn], first[maxn];
double dis[maxn];
struct edge
{
int to, next, wt;
} e[maxm], pre[maxn];
struct node
{
int id;
double d;
bool operator < (const node &a)
const
{
return d < a.d;
}
};
void Add_Edge(int u, int v, int w)
{
cnt++;
e[cnt].wt = w;
e[cnt].to = v;
e[cnt].next = first[u];
first[u] = cnt;
}
priority_queue <struct node> q;
void push_in(int a, double b)
{
struct node temp;
temp.d = b;
temp.id = a;
q.push(temp);
}
void Dijkstra()
{
for(int i = 1; i <= n; i++)
dis[i] = inf;
dis[s] = 0;
push_in(s, 0);
while(!q.empty())
{
struct node cur = q.top();
q.pop();
int x = cur.id;
if(vis[x])
continue;
vis[x] = 1;
for(int i = first[x]; i; i = e[i].next)
{
int y = e[i].to;
if(dis[y] > dis[x] + log(e[i].wt))
{
dis[y] = dis[x] + log(e[i].wt);//求对数
pre[y].wt = e[i].wt;//记录前驱
pre[y].to = x;
}
if(!vis[y])
push_in(y, dis[y]);
}
}
}
int main()
{
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
scanf("%d %d", &n, &m);
for(int i = 1; i <= m; i++)
{
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
Add_Edge(u, v, w);
if(u == s)
dis[v] = w;
}
Dijkstra();
int ans = 1, u = n;
while(pre[u].to) //溯源
{
ans *= pre[u].wt;
ans %= mod;
u = pre[u].to;
}
printf("%d", ans % mod);
return 0;
}