传送门 Codeforces 786B Legacy
建两颗线段树 o t r , i t r otr,itr otr,itr,分别代表出点与入点。首先,对于 [ 0 , n ) [0,n) [0,n) 各点,从其入点向出点连一条边权为 0 0 0 的边。接着 o t r otr otr 上子节点向父节点连一条边权为 0 0 0 的边, i t r itr itr 上父节点向子节点连一条边权为 0 0 0 的边。
对于各个操作,以 v → [ l , r ] v\rightarrow [l,r] v→[l,r] 为例,从 v v v 在 o t r otr otr 上的编号,向 [ l , r ] [l,r] [l,r] 在 i t r itr itr 上的编号对应的节点连边,后者对应的节点数为 O ( log n ) O(\log n) O(logn)。总节点数为 O ( n + q log n ) O(n+q\log n) O(n+qlogn)。以 s s s 的入点为起点跑 D i j k s t r a Dijkstra Dijkstra 即可。
#include
using namespace std;
#define pb push_back
typedef long long ll;
typedef pair<ll, int> pii;
const int MAXN = 1E5 + 5, SZ = 1 << 18;
const ll INF = 0x3f3f3f3f3f3f3f3f;
int N, Q, S;
int in[MAXN], out[MAXN];
struct edge
{
int to, cost;
};
vector<edge> G[SZ << 1];
void add_edge(int u, int v, int w) { G[u].pb({v, w}); }
struct ST
{
int bs;
void set(int b) { bs = b; }
void init(int k = 0, int l = 0, int r = N)
{
if (r - l == 1)
{
k += bs;
bs == 0 ? out[l] = k : in[l] = k;
return;
}
int m = (l + r) / 2, chl = k * 2 + 1, chr = k * 2 + 2;
init(chl, l, m), init(chr, m, r);
k += bs, chl += bs, chr += bs;
if (bs == 0)
add_edge(chl, k, 0), add_edge(chr, k, 0);
else
add_edge(k, chl, 0), add_edge(k, chr, 0);
}
void change(int a, int b, int v, int w, int k = 0, int l = 0, int r = N)
{
if (r <= a || b <= l)
return;
if (a <= l && r <= b)
{
k += bs;
bs == 0 ? add_edge(k, in[v], w) : add_edge(out[v], k, w);
return;
}
int m = (l + r) / 2, chl = k * 2 + 1, chr = k * 2 + 2;
change(a, b, v, w, chl, l, m), change(a, b, v, w, chr, m, r);
}
} itr, otr;
ll ds[SZ << 1];
bool used[SZ << 1];
void dijkstra(int s)
{
memset(ds, 0x3f, sizeof(ds));
memset(used, 0, sizeof(used));
ds[s] = 0;
priority_queue<pii, vector<pii>, greater<pii>> q;
q.push({0, s});
while (q.size())
{
int v = q.top().second;
q.pop();
if (used[v])
continue;
used[v] = 1;
for (auto &e : G[v])
{
ll d = ds[v] + e.cost;
if (d < ds[e.to])
ds[e.to] = d, q.push({d, e.to});
}
}
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> N >> Q >> S;
--S;
itr.set(SZ), otr.set(0);
itr.init(), otr.init();
for (int v = 0; v < N; ++v)
add_edge(in[v], out[v], 0);
for (int i = 0; i < Q; ++i)
{
int op;
cin >> op;
if (op == 1)
{
int u, v, w;
cin >> u >> v >> w;
--u, --v;
add_edge(out[u], in[v], w);
}
else
{
int v, l, r, w;
cin >> v >> l >> r >> w;
--v, --l;
op == 2 ? itr.change(l, r, v, w) : otr.change(l, r, v, w);
}
}
dijkstra(in[S]);
for (int v = 0; v < N; ++v)
cout << (ds[in[v]] == INF ? -1 : ds[in[v]]) << (v + 1 == N ? '\n' : ' ');
return 0;
}