【BZOJ3265】志愿者招募加强版【单纯形法】

裸哒,抄了个模板,但是跑的有点慢了...


/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#include <cmath>

typedef double DB;
typedef long long LL;

const int maxn = 1005, maxm = 10005;
const DB inf = 0x3f3f3f3f3f3f3f3f, eps = 1e-7;

int n, m;
DB b[maxm], c[maxn], cof[maxm][maxn], ans;

inline void pivot(int id, int pos) {
	b[id] /= cof[id][pos];
	cof[id][pos] = 1 / cof[id][pos];
	for(int i = 1; i <= n; i++) if(i != pos) cof[id][i] *= cof[id][pos];
	
	for(int i = 1; i <= m; i++) if(i != id && fabs(cof[i][pos]) > eps) {
		b[i] -= cof[i][pos] * b[id];
		for(int j = 1; j <= n; j++) if(j != pos) cof[i][j] -= cof[i][pos] * cof[id][j];
		cof[i][pos] = -cof[i][pos] * cof[id][pos];
	}

	ans += c[pos] * b[id];
	for(int i = 1; i <= n; i++) if(i != pos) c[i] -= c[pos] * cof[id][i];
	c[pos] = -c[pos] * cof[id][pos];
}	

inline DB simplex() {
	while(1) {
		int pos, id;
		for(pos = 1; pos <= n; pos++) if(c[pos] > eps) break;
		if(pos == n + 1) return ans;

		DB tmp = inf;
		for(int i = 1; i <= m; i++) if(cof[i][pos] > eps && b[i] / cof[i][pos] < tmp)
			tmp = b[i] / cof[i][pos], id = i;
		if(tmp == inf) return inf;
		pivot(id, pos);
	}
}

int main() {
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= n; i++) scanf("%lf", &c[i]);
	for(int i = 1; i <= m; i++) {
		int k; scanf("%d", &k);
		while(k--) {
			int x, y; scanf("%d%d", &x, &y);
			for(int j = x; j <= y; j++) cof[i][j] = 1;
		}
		scanf("%lf", &b[i]);
	}

	printf("%lld\n", LL(simplex() + 0.5));
	return 0;
}


你可能感兴趣的:(线性规划,单纯形法)