NC24760. [USACO 2010 Dec G]Big Macs Around the World
描述
输入描述
* Line 1: Five space-separated numbers: N, M, V, A, B
* Lines 2..M+1: Three space-separated numbers: i, j,
输出描述
* Line 1: A single positive number, the price of the Big Mac, with absolute or relative error at most . If there is no minimum, output 0.
示例1
输入:
3 4 60 1 2 1 2 0.2 1 3 5 3 2 0.5 2 1 5
输出:
12.00
C++14(g++5.4) 解法, 执行用时: 1061ms, 内存消耗: 1388K, 提交时间: 2019-10-13 21:29:38
#include <bits/stdc++.h> using namespace std; const int N = 200010; int n, m, a, b, x, y; long double v, w; struct node { int to, next; long double val; } indexx[N]; int cnt, head[N], Hash[N]; void add(int x, int y, long double w) { indexx[++cnt].to = y; indexx[cnt].next = head[x]; indexx[cnt].val = w; head[x] = cnt; } long double l[N]; bool vis[N], flag; void spfa() { queue<int> q; for (int i = 1; i <= n; i++) l[i] = 1e16; l[a] = v; q.push(a); vis[a] = 1; while (q.size()) { int u = q.front(); q.pop(); vis[u] = 0; for (int i = head[u]; i; i = indexx[i].next) { int to = indexx[i].to; if (l[to] > l[u] * indexx[i].val) { l[to] = l[u] * indexx[i].val; if (!vis[to]) { q.push(to); vis[to] = 1; Hash[to]++; if (Hash[to] > n) { flag = 1; break; } } } } } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); scanf("%d%d%Lf%d%d", &n, &m, &v, &a, &b); for (int i = 1; i <= m; i++) { scanf("%d%d%Lf", &x, &y, &w); add(x, y, w); } spfa(); printf("%Lf\n", flag == 1 ? 0 : l[b]); return 0; }
C++(clang++ 11.0.1) 解法, 执行用时: 111ms, 内存消耗: 1628K, 提交时间: 2022-10-20 16:32:03
#include<bits/stdc++.h> using namespace std; int n,m,a,b; #define ll long long double v; const ll LNF=0x3f3f3f3f3f3f3f3f; const int N=2e5+10,M=35000; int h[N],e[N],ne[N],cnt[N]; double w[N],d[N]; bool vis[N]; int idx; void add(int x,int y,double z) { w[idx]=z; e[idx]=y; ne[idx]=h[x]; h[x]=idx++; } bool dij() { for(int i = 0;i<=n;++i) d[i] = 1e16; d[a]=v; queue<int>q; q.push(a); while(!q.empty()) { int t=q.front(); q.pop(); vis[t]=0; for(int i=h[t];i!=-1;i=ne[i]) { int j=e[i]; if(d[j]>d[t]*w[i]) { d[j]=d[t]*w[i]; cnt[j]=cnt[t]+1; if(cnt[j]>=n) { return false; } if(!vis[j]) { vis[j]=1; q.push(j); } } } } return true; } int main() { cin>>n>>m>>v>>a>>b; memset(h,-1,sizeof(h)); while(m--) { int i,j; double dis; cin>>i>>j>>dis; add(i,j,dis); } bool st=dij(); if(!st)cout<<"0\n"; else printf("%.2lf\n",d[b]); }