1. 程式人生 > 實用技巧 >換教室sol

換教室sol

換教室

  • 概率期望dp的模板題
  • 狀態較好設計,轉移的時候注意要把所有的可能性都考慮到並加起來
#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define SZ(x) ((int)x.size())
#define ALL(x) x.begin(),x.end()
#define U(i,u) for(register int i=head[u];i;i=nxt[i])
#define rep(i,a,b) for(register int i=(a);i<=(b);++i)
#define per(i,a,b) for(register int i=(a);i>=(b);--i)
using namespace std;
typedef long double ld;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int,int> PII;
typedef vector<int> VI;
template<class T> inline void read(T &x){
	x=0;char c=getchar();int f=1;
	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
	while(isdigit(c)){x=x*10+c-'0';c=getchar();}x*=f;
}
template<class T> inline void cmin(T &x, T y){x=x<y?x:y;}
template<class T> inline void cmax(T &x, T y){x=x>y?x:y;}
inline double xmin(double x, double y){return x<y?x:y;}
const int N=2010;
int n,m,cv,ce;
int c[N],d[N];
int g[N][N];
double p[N];
double f[N][N][2];
int main(){
	read(n);read(m);read(cv);read(ce);
	rep(i,1,n)read(c[i]);rep(i,1,n)read(d[i]);rep(i,1,n)scanf("%lf",&p[i]);
	memset(g,0x3f,sizeof(g));
	rep(i,1,ce){int x,y,z;read(x);read(y);read(z);g[x][y]=g[y][x]=min(g[x][y],z);}
	rep(i,1,cv)g[i][i]=0;
	rep(k,1,cv){
		rep(i,1,cv){
			rep(j,1,cv){
				if(g[i][j]>g[i][k]+g[k][j])
					g[i][j]=g[i][k]+g[k][j];
			}
		}
	}
	rep(i,1,cv)g[0][i]=g[i][0]=0;
	rep(i,0,n)rep(j,0,m)f[i][j][0]=f[i][j][1]=0x3f3f3f3f;
	f[1][1][1]=f[1][0][0]=0.0;
	rep(i,2,n){
		f[i][0][0]=f[i-1][0][0]+g[c[i-1]][c[i]];
		rep(j,1,min(i,m)){
			f[i][j][0]=xmin(f[i][j][0],xmin(f[i-1][j][1]+double(g[d[i-1]][c[i]])*p[i-1]+double(g[c[i-1]][c[i]])*(1-p[i-1]),f[i-1][j][0]+double(g[c[i-1]][c[i]])));
			f[i][j][1]=xmin(f[i][j][1],xmin(f[i-1][j-1][0]+double(g[c[i-1]][d[i]])*p[i]+double(g[c[i-1]][c[i]])*(1-p[i]),f[i-1][j-1][1]+double(g[c[i-1]][c[i]])*(1-p[i])*(1-p[i-1])+double(g[c[i-1]][d[i]])*p[i]*(1-p[i-1])+double(g[d[i-1]][c[i]])*p[i-1]*(1-p[i])+double(g[d[i-1]][d[i]])*p[i-1]*p[i]));
		}
	}
	double ans=0x3f3f3f3f;
	rep(i,0,m)ans=xmin(ans,xmin(f[n][i][0],f[n][i][1]));
	printf("%.2f",ans);
	return 0;
}
// xmin(f[i-1][j-1][0]+double(g[c[i-1]][d[i]])*p[i]+double(g[c[i-1]][c[i]])*(1-p[i]),
// 	 f[i-1][j-1][1]
// 	 +double(g[c[i-1]][c[i]])*(1-p[i])*(1-p[i-1])
// 	 +double(g[c[i-1]][d[i]])*p[i]*(1-p[i-1])
// 	 +double(g[d[i-1]][c[i]])*p[i-1]*(1-p[i])
// 	 +double(g[d[i-1][d[i]]])*p[i-1]*p[i])