J Free

J Free

链接:https://ac.nowcoder.com/acm/contest/884/J

Problem

Your are given an undirect connected graph.Every edge has a cost to pass.You should choose a path from S to T and you need to pay for all the edges in your path. However, you can choose at most k edges in the graph and change their costs to zero in the beginning. Please answer the minimal total cost you need to pay.

输入描述:

The first line contains five integers n,m,S,T,K.

For each of the following m lines, there are three integers a,b,l, meaning there is an edge that costs l between a and b.

n is the number of nodes and m is the number of edges.

输出描述:

An integer meaning the minimal total cost.

示例1

输入

3 2 1 3 1
1 2 1
2 3 2
  •  

输出

1
  •  

备注:

1 <= n,m <= 103,1 <= S,T,a, b <= n, 0 <= k <= m,1 <= 106
.
Multiple edges and self loops are allowed.

题意

在一个无向图上,问起点S到终点T的最短路径,其中最多有k次机会可以直接通过一条边而不计算边权

分析

迪杰斯特拉算法
dis[i][j]表示到达i点,已经改了j次边权,此时的最短路。

相当于将原图复制成了k层,每改变一次,就向下走一层。

两种情况(如果可以变优):

(1)不用变0技能:转移到dis[dest][j] = dis[now][j] + len

(2)用变0技能:转移到dis[dest][j+1] = dis[now][j]

还有此题卡spfa,要用dijkstra。

因为dijkstra每次处理的点,最小值都已经确定。

所以第一次now.idx == n的时候,now.dis即为答案。

 

参考:https://blog.csdn.net/weixin_42664622/article/details/97625975

#include<iostream>
#include<vector>
#include<queue> 
using namespace std;

const int MAXN = 1e3+10;
const int MAXK = 1e3+10;
const int INF = 0x3f3f3f3f; 
struct edge{
	int to,cost;
	edge(){}
	edge(int to,int cost):to(to),cost(cost){} 
};
int n,m,S,T,K;
vector<edge>edges[MAXN];

struct node{
	int dest,cnt,cost;
	node(int dest,int cnt,int cost):dest(dest),cnt(cnt),cost(cost){}
	
	bool operator<(const node &b) const {
		return cost>b.cost;
	} 
	
};

int dp[MAXN][MAXK];
int dijkstra(int start,int dst){
	fill(dp[0],dp[0]+MAXN*MAXK,INF);
	priority_queue<node> que;
	
	que.push(node(start,0,0));
	dp[start][0] = 0;
	while(!que.empty()){
		node  temp = que.top(); que.pop();
		if(temp.dest == dst) return dp[dst][temp.cnt];
		if(dp[temp.dest][temp.cnt] < temp.cost) continue;
		
		for(int i = 0;i<edges[temp.dest].size();i++){
			edge e = edges[temp.dest][i];
			if(dp[e.to][temp.cnt] > temp.cost + e.cost ){
				dp[e.to][temp.cnt] = temp.cost + e.cost; 
				que.push(node(e.to,temp.cnt,dp[e.to][temp.cnt]));
			}
			
			if(dp[e.to][temp.cnt+1] > temp.cost && temp.cnt+1 <=K){
				dp[e.to][temp.cnt+1] = temp.cost; 
				que.push(node(e.to,temp.cnt+1,dp[e.to][temp.cnt+1]));
			}
		}
	}
	
	return INF;

}


int main(){
	
	cin>>n>>m>>S>>T>>K;
	
	int a,b,l;
	for(int i=0;i<m;i++){
		cin>>a>>b>>l;
		edges[a].push_back(edge(b,l));
		edges[b].push_back(edge(a,l));
	}
	
	int ans = dijkstra(S,T);
	
	printf("%d\n",ans);

	return 0;
} 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值