思路代码参考:
https://blog.csdn.net/SongBai1997/article/details/81489374
问题描述
小明和小芳出去乡村玩,小明负责开车,小芳来导航。
小芳将可能的道路分为大道和小道。大道比较好走,每走1公里小明会增加1的疲劳度。小道不好走,如果连续走小道,小明的疲劳值会快速增加,连续走s公里小明会增加s2的疲劳度。
例如:有5个路口,1号路口到2号路口为小道,2号路口到3号路口为小道,3号路口到4号路口为大道,4号路口到5号路口为小道,相邻路口之间的距离都是2公里。如果小明从1号路口到5号路口,则总疲劳值为(2+2)2+2+22=16+2+4=22。
现在小芳拿到了地图,请帮助她规划一个开车的路线,使得按这个路线开车小明的疲劳度最小。
输入格式
输入的第一行包含两个整数n, m,分别表示路口的数量和道路的数量。路口由1至n编号,小明需要开车从1号路口到n号路口。
接下来m行描述道路,每行包含四个整数t, a, b, c,表示一条类型为t,连接a与b两个路口,长度为c公里的双向道路。其中t为0表示大道,t为1表示小道。保证1号路口和n号路口是连通的。
输出格式
输出一个整数,表示最优路线下小明的疲劳度。
样例输入
6 7
1 1 2 3
1 2 3 2
0 1 3 30
0 3 4 20
0 4 5 30
1 3 5 6
1 5 6 1
样例输出
76
样例说明
从1走小道到2,再走小道到3,疲劳度为52=25;然后从3走大道经过4到达5,疲劳度为20+30=50;最后从5走小道到6,疲劳度为1。总共为76。
数据规模和约定
对于30%的评测用例,1 ≤ n ≤ 8,1 ≤ m ≤ 10;
对于另外20%的评测用例,不存在小道;
对于另外20%的评测用例,所有的小道不相交;
对于所有评测用例,1 ≤ n ≤ 500,1 ≤ m ≤ 105,1 ≤ a, b ≤ n,t是0或1,c ≤ 105。保证答案不超过106。
代码
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#include <algorithm>
using namespace std;
const int MAXN = 500 + 10;
const int INF = INT_MAX;
typedef long long ll;
struct Edge{//各边的信息,用于图的邻接表存储
int to;//边的另一个端点
int length;//边的长度
int type;//边的类型 1:小路 0:大路
Edge(int t,int l,int _type):to(t),length(l),type(_type){}
};
ll fatigue[MAXN];//记录到达个点最小的疲劳度
int little[MAXN];//记录疲劳度最小的情况下,以该点为终点的小路的长度
bool visit[MAXN];//标记各个点是否被访问过
vector<Edge> graph[MAXN];//图的邻接表存储
struct Point{//点的信息,用于Dijkstra的优先队列
int number;//各点的编号
ll tired;//最小的疲劳度
Point(int n,int t):number(n),tired(t){}
bool operator < (const Point& point) const{//小于号重载
return tired > point.tired;//疲劳度小的优先级大
}
};
void Dijkstra(int start,int n){
fill(fatigue,fatigue+n+1,INF);//先将所有点的疲劳度都设置为无穷大
fill(little,little+n+1,0);//将所有点前边连续的小路长度设置为0
fill(visit,visit+n+1,false);//将所有点都标记为未访问过
fatigue[start] = 0;//开始结点的疲劳度为0
priority_queue<Point>que;
que.push(Point(1,0));//将开始结点加入到优先队列中
while(!que.empty()){//队列不为空时进行循环
int current = que.top().number;
que.pop();
if(!visit[current]){//队首元素未被访问时
visit[current] = true;//访问它
for(int i=0;i<graph[current].size();i++){//处理该点的邻接点
int now = graph[current][i].to;//邻接点编号为now
if(visit[now]){
continue;
}
ll cost = 0;//记录now的最小的疲劳值
if(graph[current][i].type){//若为小路
//temp记录以now作为终点的小路的长度
//以current作为终点的小路的长度,加上两点之间的距离
ll temp = little[current] + graph[current][i].length;
//先用current的疲劳度减去current小路消耗的疲劳度
//在加上now之前小路长度temp的平方
cost = fatigue[current] - little[current] * little[current] + temp * temp;
}else{
//若为大路,直接加上大路的长度即为疲劳度
cost = fatigue[current] + graph[current][i].length;
}
if(cost < fatigue[now]){//松弛操作
fatigue[now] = cost;//更新疲劳度的值
//更新小路长度
if(graph[current][i].type){
little[now] = little[current] + graph[current][i].length;
}else{
little[now] = 0;
}
//将更新的点加入到队列中
que.push(Point(now,fatigue[now]));
}
}
}
}
}
int main(){
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++){
int type,from,to,length;
cin>>type>>from>>to>>length;
//无向图,故两个路口(点)要互加到对方的邻接点中
graph[from].push_back(Edge(to,length,type));
graph[to].push_back(Edge(from,length,type));
}
Dijkstra(1,n);//起点,路口数(点的个数)
cout<<fatigue[n];
return 0;
}