【UVA10498】—Happiness(线性规划/单纯形算法)

传送门


题解:

模板题(抄代码)
奇怪的精度

#include
using namespace std;
const int RLEN=1<<20|1;
inline char gc(){
	static char ibuf[RLEN],*ib,*ob;
	(ib==ob)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
	return (ob==ib)?EOF:*ib++;
} 
inline int read(){
	char ch=gc();
	int res=0,f=1;
	while(!isdigit(ch))f^=ch=='-',ch=gc();
	while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
	return f?res:-res;
}
const int N=25;
const double eps=1e-12,inf=1e17;
int n,m;
double a[N][N];
inline void povit(int l,int e){
	double t=a[l][e];a[l][e]=1;
	for(int j=0;j<=n;j++)a[l][j]/=t;
	for(int i=0;i<=m;i++)if(l!=i&&fabs(a[i][e])>0){
		t=a[i][e],a[i][e]=0;
		for(int j=0;j<=n;j++)a[i][j]-=t*a[l][j];
	}
}
inline void simplex(){
	while(1){
		int l=0,e=0;double mn=inf;
		for(int j=1;j<=n;j++)if(a[0][j]>eps){e=j;break;}
		if(!e)break;
		for(int i=1;i<=m;i++)if(a[i][e]>eps&&a[i][0]/a[i][e]<mn)
			mn=a[i][0]/a[i][e],l=i;
		povit(l,e);
	}
}
int main(){
	while(~scanf("%d%d",&n,&m)){
		for(int i=1;i<=n;i++)scanf("%lf",&a[0][i]);
		for(int i=1;i<=m;i++){
			for(int j=1;j<=n;j++)scanf("%lf",&a[i][j]);
			scanf("%lf",&a[i][0]);
		}	
		a[0][0]=0;
		simplex();
		printf("Nasa can spend %lld taka.\n",(long long)floor(-a[0][0]*m+1.0-eps));
	}
}

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