当前位置:网站首页>【2022杭电多校5 1003 Slipper】多个超级源点+最短路
【2022杭电多校5 1003 Slipper】多个超级源点+最短路
2022-08-04 20:44:00 【宇智波一打七~】
题目描述

输入

输出

样例输入
1
6
6 1 2
3 5 2
2 4 6
5 2 2
5 6 20
3 8
6 5
样例输出
12
题意
一棵树,每条边上有权值,然后可以以p的代价传送到距离当前节点k层的任意节点,p是输入给出的,现在给你一个起点和一个终点,问从起点到终点的最短花费是多少。
思路
除了能传送这个条件其他就是一个最短路,如果相距k层的每个点都都建一条边的话那么边就太多了,然后就可以想到在每一层建一个超级源点,这个超级源点距离这一层的点的距离是0,与距离这一层为k的超级源点的距离是p,然后wa掉了,因为只建立一个超级源点的话就会使得同一层的任意两个点的距离变成0,这是不成立的,然后就可以每一层建两个超级源点,一个进,一个出,这样问题就迎刃而解了,先来看一下这个样例图吧,每一层的蓝色点就是出点,红色点就是入点。
下面看代码吧:
#include<bits/stdc++.h>
using namespace std;
const int N = 5e6+10;
typedef long long LL;
int h[N],e[N+N],ne[N+N];
int w[N+N],idx;
void add(int a,int b,int c){
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx++;
}
vector<int> de[N];
int n,k,p;
LL dis[N];
bool st[N];
int mx;
void dfs(int u,int fa,int deep){
de[deep].push_back(u);
mx = max(mx,deep);
for(int i=h[u];i!=-1;i=ne[i]){
int v = e[i];
if(v == fa) continue;
dfs(v,u,deep+1);
}
}
typedef pair<LL,int> PII;
void solve(){
scanf("%d",&n);
idx = 0;
mx = 0;
for(int i=1;i<=4*n;i++){
h[i] = -1;
dis[i] = 0x3f3f3f3f3f3f3f3fll;
de[i].clear();
st[i] = false;
}
for(int i=1;i<n;i++){
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
scanf("%d%d",&k,&p);
dfs(1,0,1);
for(int i=1;i<=mx;i++){
for(auto u : de[i]){
add(u,n+i*2-1,0);
add(i*2+n,u,0);
}
if(i+k>mx) continue;
add(n+i*2-1,n+(i+k)*2,p);
add(n+(i+k)*2-1,n+i*2,p);
}
int sta,ed;
scanf("%d%d",&sta,&ed);
priority_queue<PII,vector<PII>,greater<PII> > q;
dis[sta] = 0;
q.push(make_pair(0,sta));
while(q.size()){
int t = q.top().second;
q.pop();
if(st[t]) continue;
if(t == ed) break;
st[t] = true;
for(int i=h[t];i!=-1;i=ne[i]){
int j = e[i];
if(dis[j] > dis[t] + w[i]){
dis[j] = dis[t] + w[i];
if(!st[j]) q.push({
dis[j],j});
}
}
}
printf("%lld\n",dis[ed]);
}
int main(){
int _;
scanf("%d",&_);
while(_--) solve();
return 0;
}
边栏推荐
猜你喜欢
随机推荐
Uniapp微信雪糕刺客单页小程序源码
MySQL stored procedure introduction, creation, case, delete, view "recommended collection"
[Data Mining] Written Exam Questions for Sohu Data Mining Engineers
Debug locally and start the local server in vs code
用 Excel 爬取网络数据的四个小案例
遇到MapStruct后,再也不手写PO,DTO,VO对象之间的转换了
Unreal 本地化 国家化 多语言
After encountering MapStruct, the conversion between PO, DTO and VO objects is no longer handwritten
Nuxt.js的优缺点和注意事项
C语言——青蛙跳台阶(递归)
Go study notes (Part 1) Configuring the Go development environment
刷题-洛谷-P1200 你的飞碟在这儿Your Ride Is Here
如何用好建造者模式
【AGC】构建服务1-云函数示例
长时间序列遥感数据处理及在全球变化、物候提取、植被变绿与固碳分析、生物量估算与趋势分析等领域中的应用
【一起学Rust | 进阶篇 | Service Manager库】Rust专用跨平台服务管理库
工龄10年的测试员从大厂“裸辞”后...
vehemently condemn
SAP ABAP OData 服务如何支持 $select 有选择性地仅读取部分模型字段值试读版
win10终端中如何切换磁盘









