Edward, the emperor of the Marjar Empire, wants to build some bidirectional highways so that he can reach other cities from the capital as fast as possible. Thus, he proposed the highway project.
The Marjar Empire has N cities (including the capital), indexed from 0 to N - 1 (the capital is 0) and there are M highways can be built. Building the i-th highway costs Ci dollars. It takes Di minutes to travel between city Xi and Yi on the i-th highway.
Edward wants to find a construction plan with minimal total time needed to reach other cities from the capital, i.e. the sum of minimal time needed to travel from the capital to city i (1 ≤ i ≤ N). Among all feasible plans, Edward wants to select the plan with minimal cost. Please help him to finish this task.
There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:
The first contains two integers N, M (1 ≤ N, M ≤ 105).
Then followed by M lines, each line contains four integers Xi, Yi, Di, Ci (0 ≤ Xi, Yi < N, 0 < Di, Ci < 105).
For each test case, output two integers indicating the minimal total time and the minimal cost for the highway project when the total time is minimized.
2 4 5 0 3 1 1 0 1 1 1 0 2 10 10 2 1 1 1 2 3 1 2 4 5 0 3 1 1 0 1 1 1 0 2 10 10 2 1 2 1 2 3 1 2
4 34 4
这题其实就是求一个最短路 把每次加入的边的花费加到一起就可以了,要注意的是开ll 。
#include<iostream> #include<cstdio> #include<queue> #include<vector> #include <string.h> using namespace std; typedef long long ll; const int Ni=100005; const ll INF=1e12; struct node{ int to; ll cost,dist; node(int _to,ll _dist,ll _cost) {to=_to; dist=_dist; cost=_cost;} bool operator<(const node &a) const { if(dist==a.dist && cost==a.cost) return to<a.to; else if(dist==a.dist) return cost>a.cost; else return dist>a.dist; } }; vector<node> eg[Ni]; priority_queue<node> q; bool vis[Ni]; ll dis[Ni],cost[Ni]; int n; void dijkstra(int s) { int i; for(i=0;i<n;i++) {dis[i]=INF;cost[i]=INF;} dis[s]=0; cost[s]=0; while(!q.empty()) q.pop(); q.push(node(s,dis[s],cost[s])); while(!q.empty()) { node x=q.top(); q.pop(); for(i=0;i<eg[x.to].size();i++) { node y=eg[x.to][i]; int to=y.to; int _dis=y.dist; if(dis[to]>dis[x.to]+_dis){ dis[to]=dis[x.to]+_dis; cost[to]=y.cost; q.push(node(to,dis[to],cost[to])); } else if(dis[to]==dis[x.to]+_dis && cost[to]>y.cost){ cost[to]=y.cost; q.push(node(to,dis[to],cost[to])); } } } ll ans1=0,ans2=0; for(int i=0;i<n;i++){ ans1+=dis[i]; ans2+=cost[i]; } /*for(int i=1;i<n;i++) cout<<cost[i]<<endl;*/ cout<<ans1<<" "<<ans2<<endl; } int main() { int a,b,d,m,t,v; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); memset(eg,0,(n+1)*sizeof eg[0]); memset(vis,false,sizeof(vis)); while(m--) { scanf("%d%d%d%d",&a,&b,&d,&v); eg[a].push_back(node(b,d,v)); eg[b].push_back(node(a,d,v)); } dijkstra(0); } return 0; }