Title Link
If there is a hole, I didn't expect it at first!
There are n intervals. We can put some points in [0, 10000]. Then, we ask that there are at least 2 points in each of the N intervals we give, so how many points should we put at least?
It can be thought that we can still see the difference between the sum of prefixes to represent a certain interval [l, r] can be seen as sum(r) - sum(l-1). Then, we only need to find the minimum value of sum (up).
But there is a hole in the difference constraint. If we change the initial value of dis[i] to 0 in spfa(), we will be wa! Because in this way, the later updated ones will not enter the queue. Unless we go directly from 0 to all the points with a weight of 0, we will actually be WA, which is related to the operation of SPFA () to determine the size.
Therefore, we need to make dis [i] < 0 at the beginning, just "< 0" is enough, and the specific amount is arbitrary.
#include <iostream> #include <cstdio> #include <cmath> #include <string> #include <cstring> #include <algorithm> #include <limits> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #define lowbit(x) ( x&(-x) ) #define pi 3.141592653589793 #define e 2.718281828459045 #define efs 1e-6 #define INF 0x3f3f3f3f #define HalF (l + r)>>1 #define lsn rt<<1 #define rsn rt<<1|1 #define Lson lsn, l, mid #define Rson rsn, mid+1, r #define QL Lson, ql, qr #define QR Rson, ql, qr #define myself rt, l, r #define MAX_3(a, b, c) max(max(a, b), c) using namespace std; typedef unsigned long long ull; typedef long long ll; const int maxN = 1e4 + 7, maxE = 5e4 + 7; int N, M, cnt, head[maxN], dist[maxN], used[maxN], _UP; struct node { int val, id; }a[maxN]; inline bool cmp(node e1, node e2) { return e1.val < e2.val; } struct Eddge { int nex, to, val; Eddge(int a=-1, int b=0, int c=0):nex(a), to(b), val(c) {} }edge[maxE]; inline void addEddge(int u, int v, int w) { edge[cnt] = Eddge(head[u], v, w); head[u] = cnt++; } queue<int> Q; bool inque[maxN]; inline int spfa(int st = 0, int ed = _UP) { while(!Q.empty()) Q.pop(); for(int i=0; i<=_UP; i++) { dist[i] = -INF; inque[i] = false; } Q.push(st); inque[st] = true; dist[st] = 0; while(!Q.empty()) { int u = Q.front(); Q.pop(); inque[u] = false; for(int i=head[u], v, w; ~i; i=edge[i].nex) { v = edge[i].to; w = edge[i].val; if(dist[v] < dist[u] + w) { dist[v] = dist[u] + w; if(!inque[v]) { inque[v] = true; Q.push(v); } } } } return dist[ed]; } inline void init() { cnt = 0; _UP = 0; memset(head, -1, sizeof(head)); } char op[5]; int main() { while(scanf("%d", &N) != EOF) { init(); for(int i=1, u, v; i<=N; i++) { scanf("%d%d", &u, &v); v++; addEddge(u, v, 2); _UP = max(_UP, v); } for(int i=1; i<=_UP; i++) { addEddge(i-1, i, 0); addEddge(i, i-1, -1); } printf("%d\n", spfa()); } return 0; }