P1986 元旦晚会
模板题,不讲太多。
同样是两个式子:
\[a[r] - a[l] \geq k
\]
和
\[0 \leq a[i] - a[i - 1] \leq 1
\]
建边之后,从0点为起点找最长路就对了。
差分约束差不多也就学到这里了。
代码:
#include<cstdio>
#include<cstring>
#include<queue>
const int maxn = 30005, maxm = 5005;
// s[r] - s[l - 1] >= k
// dist[v] >= dist[u] + e[i].weight
// longest path problem
// 0 <= s[i] - s[i - 1] <= 1
// s[i] - s[i - 1] >= 0
// s[i - 1] - s[i] >= -1
struct Edges
{
int next, to, weight;
} e[maxm << 2];
int head[maxn], tot;
int n, m;
std::queue<int> q;
bool vis[maxn];
int dist[maxn];
int read()
{
int ans = 0, s = 1;
char ch = getchar();
while(ch > '9' || ch < '0')
{
if(ch == '-') s = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9')
{
ans = ans * 10 + ch - '0';
ch = getchar();
}
return s * ans;
}
void link(int u, int v, int w)
{
e[++tot] = (Edges){head[u], v, w};
head[u] = tot;
}
void spfa(int s)
{
for(int i = 0; i <= n; i++) dist[i] = -19260817;
dist[s] = 0;
q.push(s); vis[s] = true;
while(!q.empty())
{
int u = q.front(); q.pop(); vis[u] = false;
for(int i = head[u]; i; i = e[i].next)
{
int v = e[i].to;
if(dist[u] + e[i].weight > dist[v])
{
dist[v] = dist[u] + e[i].weight;
if(!vis[v])
{
q.push(v); vis[v] = true;
}
}
}
}
}
int main()
{
n = read(), m = read();
while(m--)
{
int l = read(), r = read(), k = read();
link(l - 1, r, k);
}
for(int i = 1; i <= n; i++)
{
link(i - 1, i, 0);
link(i, i - 1, -1);
}
spfa(0);
printf("%d\n", dist[n]);
return 0;
}