思路
- 这题用差分约束需要找齐所有的不等式,令S[i]表示0~i之间有几个数字被放入集合里面了
- S[i]>=S[i-1]
- S[i-1]>=S[i]-1,S[i]最多比S[i-1]大1
- S[b]-S[a-1]>=c
- 根据以上不等式建立图
代码1
- 这里就是最朴素的建图法,最后把N-1这个点作为超级原点来连接每个点
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 50010, M = 150010;
int n;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
queue<int> q;
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
void spfa()
{
memset(dist, -0x3f, sizeof dist);
dist[N-1] = 0;
st[N-1] = true;
q.push(N-1);
while (q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (dist[j] < dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
if (!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
}
int main()
{
scanf("%d", &n);
memset(h, -1, sizeof h);
for (int i = 0; i < N-1; i ++ )
{
add(i - 1, i, 0);
add(i, i - 1, -1);
}
for (int i = 0; i < n; i ++ )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
a, b;
add(a - 1, b, c);
}
for(int i=0;i<N-1;i++){
add(N-1,i,0);
}
spfa();
printf("%d\n", dist[50001]);
return 0;
}
代码2
- 这里也可以把[a,b]区间往右移动一个单位,这样就可以空出来S[0]这个点,作为超级原点
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 50010, M = 150010;
int n;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
queue<int> q;
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
void spfa()
{
memset(dist, -0x3f, sizeof dist);
dist[0] = 0;
st[0] = true;
q.push(0);
while (q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (dist[j] < dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
if (!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
}
int main()
{
scanf("%d", &n);
memset(h, -1, sizeof h);
for (int i = 1; i < N; i ++ )
{
add(i - 1, i, 0);
add(i, i - 1, -1);
}
for (int i = 0; i < n; i ++ )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
a ++, b ++ ;
add(a - 1, b, c);
}
spfa();
printf("%d\n", dist[50001]);
return 0;
}