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;
}