Tag: binary DP Gray code
Title Address: HDU 5375
Test instructions: give you a binary string with '? ' The location can be determined by you to fill in ' 1 ' or ' 0 ', complete after the conversion into gray code, each location has a weight a[i], only gray code for ' 1 ' bit can add weights, ask you the final weights and the maximum number of.
Idea: The first thing to understand is how binary code and gray code are converted:
Dp[i][0] Indicates the maximum value at the time of the I-bit is 0, and dp[i][1] represents the maximum value at the time of 1. The maximum value for the I-bit is obtained by dp[i-1][0],dp[i-1][1] and the current weight a[i]. The current bit of binary code has 0, 1,? Three cases, so we will discuss these three kinds of situations.
#include <stdio.h>#include <math.h>#include <string.h>#include <stdlib.h>#include <iostream>#include <sstream>#include <algorithm>#include <set>#include <queue>#include <stack>#include <map>#pragma COMMENT (linker, "/stack:102400000,102400000")using namespace STD;typedef__int64 LL;Const intinf=0x3f3f3f3f;Const DoublePi=ACOs(-1.0);Const Doubleesp=1e-7;Const intmaxn=200010;CharSTR[MAXN];intA[MAXN];intdp[maxn][2];intMain () {intT,i,j;intMax;intIcase=1;scanf("%d", &t); while(t--) {scanf('%s ', str);intlen=strlen(str);memset(dp,-1,sizeof(DP)); for(i=0; i<len;i++)scanf("%d", &a[i]);if(str[0]=='? ') {dp[0][0]=0; dp[0][1]=a[0]; }Else if(str[0]==' 0 ') {dp[0][0]=0; }Else if(str[0]==' 1 ') {dp[0][1]=a[0]; } for(i=1; i<len;i++) {if(str[i]=='? ') {Max=-inf;if(dp[i-1][0]!=-1) Max=max (max,dp[i-1][0]);if(dp[i-1][1]!=-1) Max=max (max,dp[i-1][1]+a[i]); dp[i][0]=max; Max=-inf;if(dp[i-1][0]!=-1) Max=max (max,dp[i-1][0]+a[i]);if(dp[i-1][1]!=-1) Max=max (max,dp[i-1][1]); dp[i][1]=max; }Else if(str[i]==' 0 ') {Max=-inf;if(dp[i-1][0]!=-1) Max=max (max,dp[i-1][0]);if(dp[i-1][1]!=-1) Max=max (max,dp[i-1][1]+a[i]); dp[i][0]=max; }Else if(str[i]==' 1 ') {Max=-inf;if(dp[i-1][0]!=-1) Max=max (max,dp[i-1][0]+a[i]);if(dp[i-1][1]!=-1) Max=max (max,dp[i-1][1]); dp[i][1]=max; } }printf("Case #%d:%d\n", Icase++,max (dp[len-1][0],dp[len-1][1])); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU 5375 (2015 + school 7)-gray code (DP)