D. Edge Deletion(堆优化最短路)

Problem - D - Codeforces

给定一个由 n 个顶点和 m 条边组成的无向连通加权图。将从顶点 1 到顶点 i 的最短路径长度表示为 di。

你必须删除一些图中的边,使得最多只保留 k 条边。如果在删除边后,仍然存在从 1 到 i 的路径,其长度为 di,则称顶点 i 是好的。

你的目标是以这样的方式删除边,以使好的顶点数最大化。

输入格式 第一行包含三个整数 n、m 和 k(2≤n≤3⋅105,1≤m≤3⋅105,n−1≤m,0≤k≤m)- 图中的顶点和边的数量以及可以保留在图中的最大边数。

接下来 m 行,每行包含三个整数 x、y、w(1≤x,y≤n,x≠y,1≤w≤109),表示连接顶点 x 和 y 的边具有权值 w。

给定的图是连通的(任何顶点都可以从任何其他顶点到达)并且简单(不存在自环,并且对于每个无序顶点对,最多存在一条连接这些顶点的边)。

输出格式 第一行输出 e - 应该保留在图中的边数(0≤e≤k)。

第二行输出 e 个不同的整数,介于1和m之间,表示应该保留在图中的边的索引。边按照它们在输入中给出的顺序编号。好点的数量应尽可能大。

Examples

input

Copy

3 3 2
1 2 1
3 2 1
1 3 3

output

Copy

2
1 2 

input

Copy

4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5

output

Copy

2
3 2 

题解:
要想好点最多,我们应该保证在我们图中,被松弛的边尽可能少,那么如何才能得到呢

其实就是考察了堆优化最短路的定义,每次取距离源点最近的点,然后把与这点的相连的边松弛,

这样是最优的,那么我们从队列中取k+1次未遍历过的点,停止即可,

#include <cstdio>
#include <cstring>
#include <algorithm>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
#define int long long
typedef pair<int,int> PII;
int mod = 1e9 + 7;
int dis[300050];
int vis[300050];
struct node
{
	int w,id,ne;
	friend bool operator <(const node &a,const node &b)
	{
		return a.w > b.w;
	}
};
vector<node> p[300050];
void solve()
{
	int n,m,k;
	cin >> n >> m >> k;
	memset(dis,0x3f,sizeof dis);
	for(int i = 1;i <= m;i++)
	{
		int l,r,w;
		cin >> l >>r >> w;
		p[l].push_back({w,i,r});
		p[r].push_back({w,i,l});
	}
	priority_queue<node> q;
	dis[1] = 0;
	q.push({0,0,1});
	vector<int> ans;
	while(q.size()&&ans.size() <= k)
	{
		node t = q.top();
		q.pop();
		if(vis[t.ne])
		continue;
		vis[t.ne] = 1;
		ans.push_back(t.id);
		for(node ne:p[t.ne])
		{
			int j = ne.ne;
			if(dis[j] > dis[t.ne] + ne.w)
			{
				dis[j] = dis[t.ne] + ne.w;
				q.push({dis[j],ne.id,j});
			}
		}
	}
	cout << ans.size() - 1<<"\n";
	for(int i = 1;i < ans.size();i++)
	cout << ans[i] <<" ";
}
signed main()
{
//	ios::sync_with_stdio(0 );
//	cin.tie(0);cout.tie(0);
	int t = 1;
//	cin >> t;
	while(t--)
	{
		solve(); 
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值