拆点加dijkstra
虽然官网可以100分过,但是不推荐第一个算法,因为一旦出现n提前结束这个剪枝运气比较好,推荐用堆优化的dijkstra算法。
1.朴素的dijkstra
#include<iostream>
#include<cstring>
using namespace std;
int n,m;
const int N=510;
const int M=1010;
int g[N][N][2];
int d[N][M];//d[i][j]到达i号点连续走的小路为j的最小花费
bool v[N][M];
int dijkstra(){
memset(d,0x3f,sizeof d);
d[1][0]=0;
for(int i=1;i<n*1000;i++){
pair<int,int>p;
int t=-1;
for(int j=1;j<=n;j++)
for(int k=0;k<M;k++)
if(!v[j][k]&&(t==-1||d[j][k]<t))t=d[j][k],p={j,k};
v[p.first][p.second]=true;
if(p.first==n)return d[p.first][p.second];
for(int j=1;j<=n;j++){
d[j][0]=min(d[j][0],d[p.first][p.second]+g[p.first][j][0]);
int w=p.second+g[p.first][j][1];
if(w>1000)continue;
d[j][w]=min(d[p.first][p.second]+w*w-p.second*p.second,d[j][w]);
}
}
int res=1e6+10;
for(int j=0;j<M;j++)
res=min(d[n][j],res);
return res;
}
int main(){
cin>>n>>m;
memset(g,0x3f,sizeof g);
while(m--){
int t,a,b,c;
cin>>t>>a>>b>>c;
g[a][b][t]=min(g[a][b][t],c);
g[b][a][t]=g[a][b][t];
}
cout<<dijkstra();
}
2.堆优化的dijkstra
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
int n, m;
struct nd {
int v, l, w;
bool operator <(const nd& t)const {
return w > t.w;
}
};
const int M = 1010;
const int N = 510;
vector<pair<int, int>>g[N][2];
int d[N][M];
bool v[N][M];
void dijkstra() {
memset(d, 0x3f, sizeof d);
d[1][0] = 0;
priority_queue<nd>q;
q.push({ 1,0,0 });
while (q.size()) {
nd t = q.top();
q.pop();
if (v[t.v][t.l])continue;
v[t.v][t.l] = true;
for (pair<int, int> p : g[t.v][0]) {
if (d[p.first][0] > t.w + p.second) {
d[p.first][0] = t.w + p.second;
if (d[p.first][0] < 1e6)q.push({ p.first,0,d[p.first][0] });
}
}
for (pair<int, int> p : g[t.v][1]) {
int l = t.l + p.second;
if (l > 1000)continue;
if (d[p.first][l] > t.w - t.l * t.l + l * l) {
d[p.first][l] = t.w - t.l * t.l + l * l;
if (d[p.first][l] < 1e6)q.push({ p.first,l,d[p.first][l] });
}
}
}
int res = 1e6 + 10;
for (int i = 0; i < M; i++)
res = min(res, d[n][i]);
cout << res;
return;
}
int main() {
cin >> n >> m;
while (m--) {
int t, a, b, c;
cin >> t >> a >> b >> c;
g[a][t].push_back({ b,c });
g[b][t].push_back({ a,c });
}
dijkstra();
}