Atcoder D. Shortest Path on a Line (最短路 + 思维,建图难想

D - Shortest Path on a Line
题意:
给定 n n n 点,编号从 1 1 1 n n n,初始图没有边, m m m 次操作,每次给定 l , r , c l,r,c l,r,c,表示编号在区间 [ l , r ] [l,r] [l,r] 任意两点之间连有一条长度为 c c c 的边,求最终图中 1 1 1 n n n 的最短路。
思路:
如果 n 2 n^2 n2 建图,每两个点之间都加一条边的话,肯定会超时。那怎么办呢?我们可以把每个区间端点当做节点,然后 加入( L i , R i , C i L_i, R_i,C_i Li,Ri,Ci) 这条边。然后对于两个相邻点之间 反向加一条 权值为 0 的边 。这样既保证图连通,也不会影响1 —— n的最短路。
code:

#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define eps 1e-6
using namespace std;
const int maxn = 2e5 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll n, m;
int head[maxn], cnt;
struct Edge{
	int to, next, w;
}e[maxn];
void add(int x, int y, int z){
	e[++cnt].w = z;
	e[cnt].to = y;
	e[cnt].next = head[x];
	head[x] = cnt;
}
ll dis[maxn];
bool vis[maxn];
ll dij(int s){
	memset(dis, 0x3f, sizeof(dis));
	dis[1] = 0;
	priority_queue <pair<ll,int>, vector<pair<ll,int> > , greater<pair<ll,int> > > q;
	q.push({0, 1});
	while(!q.empty())
	{
		int x = q.top().second;q.pop();
		if(vis[x]) continue;
		vis[x] = 1;
		for(int i = head[x]; i; i = e[i].next)
		{
			int to = e[i].to;
			if(dis[to] > dis[x] + e[i].w)
			{
				dis[to] = dis[x] + e[i].w;
				q.push({dis[to], to});
			}
		}
	}
	if(dis[n] == INF) return -1;
	else return dis[n];
}
void work()
{
	cin >> n >> m;
	for(int i = 2; i <= n; ++i) add(i, i - 1, 0);
	for(int i = 1, l, r, c; i <= m; ++i){
		cin >> l >> r >> c;
		add(l, r, c);
	}	
	cout << dij(1);
}

int main()
{
	ios::sync_with_stdio(0);
//	int TT;cin>>TT;while(TT--)
	work();
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值