[UVA10498][单纯形]happiness

UVA10498
模板
Code:

#include
#define eps 1e-8
#define db double
using namespace std;
inline int read(){
	int res=0,f=1;char ch=getchar();
	while(!isdigit(ch)) {if(ch=='-') f=-f;ch=getchar();}
	while(isdigit(ch)) {res=(res<<1)+(res<<3)+(ch^48);ch=getchar();}
	return res*f;
}
const int N=55;
const db INF=1e10;
int n,m,NMA[N],MA[N];
db a[N][N],b[N],c[N],v;
db ans[N];
inline int sgn(db x){
	if(x>eps) return 1;
	if(x<eps) return -1;
	return 0;
}
inline void init(){
	for(int i=1;i<=n;i++) MA[i]=i;
	for(int i=1;i<=m;i++) NMA[i]=n+i;
	v=0;
}
inline void pivot(int l,int e){
	db tmp=a[l][e];
	b[l]/=tmp;a[l][e]=1/tmp;
	for(int i=1;i<=n;i++) if(i!=e) a[l][i]/=tmp;
	for(int i=1;i<=m;i++) if(i!=l){
		b[i]-=a[i][e]*b[l];
		for(int j=1;j<=n;j++) if(j!=e) a[i][j]-=a[i][e]*a[l][j];
		a[i][e]=-a[i][e]/tmp;
	}
	v+=b[l]*c[e];
	for(int i=1;i<=n;i++) if(i!=e) c[i]-=c[e]*a[l][i];
	c[e]*=-a[l][e];
	swap(NMA[l],MA[e]);
}
void simplex(){
	int l,s,x;
	db tmp,tmp1,tmp2,tmp3;
	while(1){
		tmp2=-INF;s=-1;
		for(int i=1;i<=n;i++) if(sgn(c[i])>0){
			tmp=INF;
			for(int k=1;k<=m;k++) if(sgn(a[k][i])>0){
				tmp3=b[k]/a[k][i];
				if(tmp3<tmp) tmp=tmp3,x=k;
			}
			if(tmp2<tmp*c[i]) s=i,l=x,tmp2=tmp*c[i];
		}
		if(s==-1) break;
		pivot(l,s);
	}
	for(int i=1;i<=n;i++){
		int j;
		for(j=1;j<=m;j++) if(NMA[j]==i) break;
		if(j<=m) ans[i]=b[j];
		else ans[i]=0;
	}
}
int main(){
	while(scanf("%d%d",&n,&m)!=-1){
		for(int i=1;i<=n;i++) scanf("%lf",&c[i]);
		for(int i=1;i<=m;i++){
			for(int j=1;j<=n;j++) scanf("%lf",&a[i][j]);
			scanf("%lf",&b[i]);
		}
		init();
		simplex();
		printf("Nasa can spend %.0lf taka.\n",ceil(v*m));
	}
	return 0;
}

你可能感兴趣的:(线性规划)