HDOJ-4725(Dijikstra算法+拆点求最短路)
The Shortest Path in Nya Graph
HDOJ-4725
- 这题是关于最短路的问题,但是和常规的最短路有点不同的就是这里多了层次这一结构。
- 为了解决这一问题可以把每一层抽象或者划分为两个点:入点和出点。
- 对于每个点,将所在层的入点和该点相连,再将该点和所在层的出点相连,权值都为0.
- 对于每一层,将该层的出点和上面一层,以及下面一层的入点相连,取值就是题目给的c。
- 对于其余的路径,则按照题意进行连接就行了。
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#include<map>
#include<cstring>
using namespace std;
const int INF=0X3F3F3F3F;
const int maxn=300005;
int n,m,c;
struct edge{
int to;
int cost;
};
struct node{
int dis;
int to;
bool operator<(const node& t)const{
return dis>t.dis;
}
};
int d[maxn];
vector<edge> edges[maxn];
int dijikstra(int s){
priority_queue<node> q;
memset(d,INF,sizeof(d));
d[s]=0;
q.push({0,s});
while(!q.empty()){
node now=q.top();
q.pop();
int v=now.to;
int dis=now.dis;
if(d[v]<dis)
continue;
for(int i=0;i<edges[v].size();i++){
int u=edges[v][i].to;
int cost=edges[v][i].cost;
if(d[u]>d[v]+cost){
d[u]=d[v]+cost;
q.push({d[u],u});
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin>>t;
int k=0;
while(t--){
cin>>n>>m>>c;
int layer;
for(int i=1;i<=maxn;i++){
edges[i].clear();
}
for(int i=1;i<=n;i++)
{
cin>>layer;
edges[i].push_back({n+(layer<<1),0});//当前点向该层的出点连边
edges[n+(layer<<1|1)].push_back({i,0});//该层的入点和当前点连边
}
for(int i=1;i<=n;i++){//总共有n层
edges[n+(i<<1)].push_back({n+((i+1)<<1|1),c});
edges[n+(i<<1)].push_back({n+((i-1)<<1|1),c});
}
int from,to,cost;
for(int i=0;i<m;i++){
cin>>from>>to>>cost;
edges[from].push_back({to,cost});
edges[to].push_back({from,cost});
}
dijikstra(1);
cout<<"Case #"<<++k<<": ";
if(d[n]==INF)
cout<<-1<<endl;
else
cout<<d[n]<<endl;
}
return 0;
}
Either Excellent or Rusty
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了