Description
You are given n closed, integer intervals [ai, bi] and n integers c1, …, cn.
Write a program that:
reads the number of intervals, their end points and integers c1, …, cn from the standard input,
computes the minimal size of a set Z of integers which has at least ci common elements with interval [ai, bi], for each i=1,2,…,n,
writes the answer to the standard output.
Input
The first line of the input contains an integer n (1 <= n <= 50000) – the number of intervals. The following n lines describe the intervals. The (i+1)-th line of the input contains three integers ai, bi and ci separated by single spaces and such that 0 <= ai <= bi <= 50000 and 1 <= ci <= bi - ai+1.
Output
The output contains exactly one integer equal to the minimal size of set Z sharing at least ci elements with interval [ai, bi], for each i=1,2,…,n.
Sample Input
5
3 7 3
8 10 3
6 8 1
1 3 1
10 11 1
Sample Output
6
题解
今天考试的原题。。。然而蒟蒻我真的是太弱了不会差分。。。大佬们都是瞬秒此题而我只有暴力。。。暴力。。。
但是!现在有了大佬的亲力传授,我!也!会!了!!!
差分约束就是把一堆不等式转化成最短/最长路径,并且要注意挖掘题目的信息。如果不等式是a[i] - a[j] >= w,那么就建一条j到i权值为w的边,然后跑dis[v] < dis[u] + w即可!注意初始值赋值为正无穷或负无穷~~(一定要牢记啊。。曾经的我其实搞过这个,现在全忘了QAQ)
代码
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n, m, l, r, c, a[50010], vis[50010], dis[50010];
struct Edge {
int v, w, next;
} e[200010];
int num = 0, h[200010];
void add(int u, int v, int w) {
num ++;
e[num].v = v;
e[num].w = w;
e[num].next = h[u];
h[u] = num;
}
deque<int> q;
void spfa(int s) {
while(!q.empty()) q.pop_back();
q.push_front(s), vis[1] = true, dis[s] = 0;
while(!q.empty()) {
int u=q.front(); q.pop_front(); vis[u] = false;
for(int i = h[u]; i; i =e[i].next) {
int v = e[i].v;
if(dis[v] < dis[u] + e[i].w) {
dis[v] = dis[u] + e[i].w;
if(! vis[v]) {
if(!q.empty()&&dis[v]>dis[q.front()]) q.push_front(v);
else q.push_back(v);
vis[v] = true;
}
}
}
}
}
int main() {
n = 0;
scanf("%d", &m);
for(int i = 1; i <= m; i ++) {
int l, r, c;
scanf("%d %d %d", &l, &r, &c);
n = max(n, r); add(l - 1, r, c);
}
for(int i = 1; i <= n; i ++)
add(i - 1, i, 0), add(i, i - 1, -1);
memset(dis, -127, sizeof(dis));
spfa(0);
printf("%d", dis[n]);
return 0;
}