1. 程式人生 > >NOIP 2016 換教室 期望DP

NOIP 2016 換教室 期望DP

傳送門

f[i][j][0]表示當前枚舉了i個教室,換了k次教室,這次不換的期望
f[i][j][1]表示當前枚舉了i個教室,換了k次教室,這次換的期望

期望就是指一共只有前i個教室,換j個教室,當前換不換的期望距離
轉移方程顯然,見程式碼

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2000 + 100;
const int INF = ( 1 << 29 ); 
int n,m,k,l, c[MAXN], d[MAXN], dis[MAXN][MAXN];
double
f[MAXN][MAXN][2], p[MAXN], ans; void init( ) { scanf( "%d%d%d%d", &n, &m, &k, &l ); for( register int i = 1; i <= n; i++ ) scanf( "%d", &c[i] ); for( register int i = 1; i <= n; i++ ) scanf( "%d", &d[i] ); for( register int i = 1; i <= n; i++ ) scanf
( "%lf", &p[i] ); for( register int i = 1; i <= k; i++ ) for( register int j = 1; j <= k; j++ ) dis[i][j] = INF; for( register int i = 1; i <= l; i++ ){ int ff, tt, ww; scanf( "%d%d%d", &ff, &tt, &ww ); if( dis[ff][tt] == INF ) dis[ff][tt] = dis[tt][ff
] = ww; else dis[ff][tt] = min( dis[ff][tt], ww ), dis[tt][ff] = dis[ff][tt]; } for( register int mid = 1; mid <= k; mid++ ) { for( register int i = 1; i <= k; i++ ) { if( i != mid ) { for( register int j = 1; j <= k; j++ ) { if( j != i && j != mid ) { dis[i][j] = min( dis[i][j], dis[i][mid] + dis[mid][j] ); } } } } } for( register int i = 1; i <= n; i++ ) for( register int j = 0; j <= m; j++ ) f[i][j][0] = f[i][j][1] = 1e30; f[1][0][0] = f[1][1][1] = 0;//f[i][j][k]表示當前選了前i個,已經換了j次教室,當前這個教室換不換所期望的花費 for(int i=1;i<=k;i++) dis[i][i]=0; for( register int i = 1; i <= k; i++ ) dis[i][i] = 0; for( register int i = 2; i <= n; i++ ) { for( register int j = 0; j <= min( i, m ); j++ ) { f[i][j][0] = min( f[i][j][0], min( f[ i - 1 ][j][0] + dis[ c[ i - 1 ] ][ c[i] ], f[ i - 1 ][j][1] + dis[ c[ i - 1 ] ][ c[i] ] * ( 1.0 - p[ i - 1 ] ) + dis[ d[ i - 1 ] ][ c[i] ] * p[ i - 1 ] ) ); if( j >
= 1 ) { f[i][j][1] = min( f[i][j][1], min( f[ i - 1 ][ j - 1 ][0] + dis[ c[ i - 1 ] ][ d[i] ] * p[i] + dis[ c[ i - 1 ] ][ c[i] ] * ( 1.0 - p[i] ), f[ i - 1 ][ j - 1 ][1] + dis[ c[ i - 1 ] ][ c[i] ] * ( 1.0 - p[ i - 1 ] ) * ( 1.0 - p[i] ) + dis[ d[ i - 1 ] ][ c[i] ] * p[ i - 1 ] * ( 1.0 - p[i] ) + dis[ d[ i - 1 ] ][ d[i] ] * p[ i - 1 ] * p[i] + dis[ c[ i - 1 ] ][ d[ i ] ] * ( 1.0 - p[ i - 1 ] ) * p[i] ) ); } } } ans = 1e30; for( register int i = 0; i <= m; i++ ) ans = min( ans, min( f[n][i][0], f[n][i][1] ) ); printf("%.2lf",ans); } int main( ) { init(); return 0; }