POJ--1752--差分约束

题目要求:
求最少个数的数字使得所有[a,b]区间内所取的个数>=k,要是b-a+1 思路:
差分约束求最少,构造>=不等式,求最长路,求完最长路后,从最小的数字开始遍历,要是dis[i+1]>dis[i],说明当前数字必须要取,则输出

#include
#include
#include
#include
#include
#include
using namespace std;
const int N = 2e4 + 10;
const int INF = 0x3f3f3f3f;
int head[N], tot;
int k, m, n;
int minn;
int dis[N], cnt[N];
bool vis[N];
struct Edge {
	int to;
	int w;
	int nxt;
}e[10*N];
void add(int u, int v, int w) {
	e[++tot].to = v;
	e[tot].nxt = head[u];
	e[tot].w = w;
	head[u] = tot;
}
bool spfa(int s) {
	for (int i = minn; i <= n; i++) {
		dis[i] = -INF;
		cnt[i] = vis[i] = 0;
	}
	dis[s] = 0;
	vis[s] = 1;
	cnt[s]++;
	queueq;
	q.push(s);
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		vis[u] = 0;
		for (int v, i = head[u]; i != -1; i = e[i].nxt) {
			v = e[i].to;
			if (dis[v] < dis[u] + e[i].w) {
				dis[v] = dis[u] + e[i].w;
				if (!vis[v]) {
					q.push(v);
					vis[v] = 1;
					cnt[v]++;
					if (cnt[v] > n - minn + 1)return false;
				}
			}
		}
	}
	return true;
}
int main() {
	scanf("%d%d", &k, &m);
	n = 0;
	memset(head, -1, sizeof(head));
	tot = 0;
	minn = 20010;  
	for (int a, b, i = 1; i <= m; i++) {
		scanf("%d%d", &a, &b);  //num[b]-num[a-1]>=k
		a += 10005;  //输入可能会有负数,添加偏差量
		b += 10005;
		if (b < a)swap(a, b);
		n = max(n, max(a, b));
		minn = min(minn, min(a, b));
		if (b - a + 1 >= k)add(a - 1, b, k);  //添加约束
		else add(a - 1, b, b - a + 1);  //当b-a+1小于k时,num[b]-num[a-1]<=b-a+1且num[b]-num[a-1]>=b-a+1,此题是找最长路,所以前面一个条件不写也可
	}
	minn -= 1;
	for (int i = minn; i < n; i++) {  //num[i+1]-num[i]>=0&&num[i+1]-num[i]<=1
		add(i, i + 1, 0);
		add(i + 1, i, -1);
	}
	spfa(minn);
	printf("%d\n", dis[n]);
	for (int i = minn+1; i <= n; i++) 
		if (dis[i] > dis[i - 1])printf("%d\n", i - 10005);
	return 0;
}

你可能感兴趣的:(POJ--1752--差分约束)