题目链接: Highway Project
题意
让你跑一段最短路,而且是从0点跑到其余的每个点,但是要求在最短时间的情况下的最小金钱cost, 输出的第一个值代表dist[1] + dist[2] + … dist[n] ,第二个值代表在最短路这个图中你走过的边的总的花费的金钱。
这个时候我们可以只记录每个节点之前的一条边的权值代表此点的cost,最后再全部相加就是所有需要的路的金钱的花费。
思路
用spfa,最短路径好求,主要是求最小的金钱花费。我们知道每个点他的前面都有一条边,我们记录的就只是他前面这条边的权值,这样的话总的金钱cost就不会重复。
代码1 spfa:
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
struct edge{
int to,next,time,money;
}edge[200100];
const int maxn = 200010;
int tot;
int head[200100];
void add(int from,int to,int time,int money)
{
edge[++tot].to = to;
edge[tot].time = time;
edge[tot].money = money;
edge[tot].next = head[from];
head[from] = tot;
}
int vis[maxn],cost[maxn];
long long dist[maxn];
int spfa(int s)
{
int k ,u,v;
dist[s] = 0;
vis[s] = 1;
queue<int>Q;
Q.push(s);
while(!Q.empty())
{
u = Q.front();
Q.pop();
vis[u] = 0 ;
for(int k = head[u]; k != -1; k = edge[k].next)
{
int time = edge[k].time;
int money = edge[k].money;
int to = edge[k].to;
if(dist[to] > dist[u] + time || (dist[to] == dist[u] + time && cost[to] > money))
{
dist[to] = dist[u] + time;
cost[to] = money;
if(!vis[to])
{
vis[to] = 1;
Q.push(to);
}
}
}
}
}
int main()
{
int t,n,m,A,B,T,M;
cin >> t;
while(t--)
{
cin >> n >> m;
tot = 0;
memset(dist,inf,sizeof(dist));
memset(vis,0,sizeof(vis));
memset(cost,inf,sizeof(cost));
memset(head,-1,sizeof(head));
for(int i = 1; i <= m; ++i)
{
cin >> A >> B >> T >> M;
add(A,B,T,M);
add(B,A,T,M);
}
spfa(0);
long long sum = 0, sum1 = 0;
for(int i = 1; i < n; ++i)
{
sum += dist[i];
sum1 += cost[i];
}
cout << sum << ' ' << sum1 << endl;
}
}
代码2 : dijkstra: (本来用的朴素dijkstra,用邻接矩阵存,写到一半发现存不了)
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 200010;
typedef pair<int,int> P1;
int n,m,tot ;
struct edge{
int v;
int next;
int time;
int money;
}edge[maxn];
int head[maxn],cost[maxn];
long long dist[maxn];
void add(int u,int v,int time,int money)
{
edge[++tot].v = v;
edge[tot].time = time;
edge[tot].money = money;
edge[tot].next = head[u];
head[u] = tot;
}
priority_queue<P1 ,vector<P1> , greater<P1> >P;
void dijkstra()
{
P.push({0,0});
dist[0] = 0;
while(!P.empty())
{
P1 A = P.top();
P.pop();
int v = A.second;
for(int k = head[v] ; k != -1; k = edge[k].next)
{
int to = edge[k].v;
int time = edge[k].time;
int money = edge[k].money;
if(dist[to] > dist[v] + time || ((dist[to] == dist[v] + time) && (cost[to] > money)))
{
dist[to] = dist[v] + time;
cost[to] = money;
P.push({dist[to],to});
}
}
}
long long sum = 0, sum1 = 0;
for(int i = 1; i < n; ++i)
{
sum += dist[i];
sum1 += cost[i];
}
cout << sum << ' ' << sum1 << endl;
}
int main()
{
int t,A,B,time,money;
cin >> t;
while(t--)
{
memset(head,-1,sizeof(head));
memset(dist,inf,sizeof(dist));
memset(cost,inf,sizeof(cost));
cin >> n >> m;
tot = 0;
for(int i = 0; i < m; ++i)
{
cin >> A >> B >> time >> money;
add(A,B,time,money);
add(B,A,time,money);
}
dijkstra();
}
}