【POJ 1716】 Integer Intervals
【题目链接】
【算法】
差分约束系统
【代码】
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; const int MAXN = 1e4 + 1; int i,n,a,b,tot; int dis[MAXN+1],head[MAXN+1]; struct Edge { int to,w,nxt; } e[MAXN<<2]; inline void add(int u,int v,int w) { tot++; e[tot] = (Edge){v,w,head[u]}; head[u] = tot; } inline int spfa() { int i,cur,v,w; queue<int> q; static bool inq[MAXN+1]; static int cnt[MAXN+1]; for (i = 1; i <= MAXN; i++) dis[i] = -1; q.push(0); inq[0] = true; cnt[0] = 1; dis[0] = 0; while (!q.empty()) { cur = q.front(); q.pop(); inq[cur] = false; for (i = head[cur]; i; i = e[i].nxt) { v = e[i].to; w = e[i].w; if (dis[cur] + w > dis[v]) { dis[v] = dis[cur] + w; if (!inq[v]) { inq[v] = true; q.push(v); cnt[v]++; if (cnt[v] > MAXN + 1) return -1; } } } } return dis[MAXN]; } int main() { scanf("%d",&n); for (i = 1; i <= n; i++) { scanf("%d%d",&a,&b); add(a,b+1,2); } for (i = 1; i <= MAXN; i++) { add(i-1,i,0); add(i,i-1,-1); } printf("%d\n",spfa()); return 0; }