K-th Path Codeforces Round #575 (Div. 3)

本文解析了CodeForces竞赛中的一道F题,题目要求找出无向图中任意两点间第K短的距离。通过重构图和使用Floyd算法,文章提供了一种有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接: https://codeforces.com/contest/1196/problem/F
题面:
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).

More formally, if d is the matrix of shortest paths, where di,j is the length of the shortest path between vertices i and j (1≤i<j≤n), then you need to print the k-th element in the sorted array consisting of all di,j, where 1≤i<j≤n.,k<=400,2≤m,n≤2e5
题意: 给你一个无向图,求出图中任意两点距离排在第K短的距离
思路: 一开始觉得这道题很难,2e5个点,想着怎么跑全图得答案,但有没有发现k最大只有400,所以我们可以想第k条小的边是不是答案呢?答案显而易见没那么简单,所以我们可以把前k条边扣出来重构一个图,跑一遍floy然后将所有距离进行排序,这时候第K小的距离就是所求的答案,所以这道题的稍微难的点就是在重构图上,我们可以将前k条边的点存起来,将点进行离散化后,将数据储存在矩阵中,图重构就完成了,全图跑一遍floy求最短路就行了

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=2e5+5;
struct node
{
	int u,v,w;
        friend bool operator <(const node &a,const node &b)
        {
        	return a.w<b.w;
        }
}edge[N];
ll mp[805][805];
int b[805];
ll dis[N];
int main()
{
	int n,m,k;
	scanf("%d%d%d",&n,&m,&k);
	for(int i=1;i<=m;i++)
	{
		scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
	}
	sort(edge+1,edge+1+m);
	int cnt=0;
	for(int i=1;i<=min(k,m);i++)
	{
		b[++cnt]=edge[i].u;
		b[++cnt]=edge[i].v;
	}
	sort(b+1,b+1+cnt);
	cnt=unique(b+1,b+1+cnt)-b-1;
	for(int i=1;i<=cnt;i++)
	for(int j=1;j<=cnt;j++)
	{
		mp[i][j]=(1ll<<60);
	}
	for(int i=1;i<=min(k,m);i++)
	{
		int u=lower_bound(b+1,b+1+cnt,edge[i].u)-b;
		int v=lower_bound(b+1,b+1+cnt,edge[i].v)-b;
		//cout<<u<<' '<<v<<endl;
		mp[u][v]=mp[v][u]=edge[i].w;
	}
	for(int k=1;k<=cnt;k++)
	{
		for(int i=1;i<=cnt;i++)
		{
			for(int j=1;j<=cnt;j++)
			{
				if(mp[i][j]>mp[i][k]+mp[k][j]){
					mp[i][j]=mp[i][k]+mp[k][j];
				}
			}
		}
	}
	int cnt1=0;
	for(int i=1;i<=cnt;i++)
	for(int j=i+1;j<=cnt;j++)
	{
		if(mp[i][j]!=(1ll<<60))
		{
			dis[++cnt1]=mp[i][j];
		}
	}
	sort(dis+1,dis+1+cnt1);
	printf("%lld\n",dis[k]);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值