hdu5375 Gray Code (DP)

Source: Internet
Author: User

Topic Links:

http://acm.hdu.edu.cn/showproblem.php?pid=5375


The main idea: 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.

Gray code means Baidu can be a bit, here can be popular point: For such a string, if I position is 1, then the number of his back will change (0 to 1, 1 to 0), note just look at the initial string. For example: The initial string is 110, then the change is 101, not 100.

IDEA: Consider a DP solution, Dp[i][j] indicates the maximum fraction (j take 0 or 1) for the first position of J.

Then there is Dp[i][0]=max (Dp[i-1][0],dp[i-1][1]+a[i]);

Dp[i][1]=max (dp[i-1][0]+a[i],dp[i-1][1]);

When J is? , the J may be 0 or 1, so long both are considered to be processed again.

Note the initialization.

#include <stdio.h> #include <math.h> #include <string.h> #define MAX (b) a>b?a:bint dp[200005][2] , A[200005];int Main () {int T,i,j,l,k,t=0;char s[200005],c[200005];scanf ("%d", &t), while (t--) {t++;scanf ("%s", s); L=strlen (s); for (i=0;i<l;i++) c[i+1]=s[i];for (i=1;i<=l;i++) scanf ('%d ', &a[i]); for (i=0;i<200005;i++) { dp[i][0]=-999999;dp[i][1]=-999999;} if (c[1]== ' 0 ') dp[1][0]=0;if (c[1]== ' 1 ') dp[1][1]=a[1];if (c[1]== '? ') {dp[1][0]=0;dp[1][1]=a[1];} for (i=2;i<=l;i++) {if (c[i]== ' 0 ') {Dp[i][0]=max (dp[i-1][0],dp[i-1][1]+a[i]);} if (c[i]== ' 1 ') {Dp[i][1]=max (dp[i-1][0]+a[i],dp[i-1][1]);} if (c[i]== '? ') {Dp[i][0]=max (dp[i-1][0],dp[i-1][1]+a[i]);DP [I][1]=max (Dp[i-1][0]+a[i],dp[i-1][1]);}} printf ("Case #%d:", T), if (c[l]== ' 0 ') printf ("%d\n", dp[l][0]), else if (c[l]== ' 1 ') printf ("%d\n", dp[l][1]), Else printf ( "%d\n", Max (dp[l][0],dp[l][1]));} return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

hdu5375 Gray Code (DP)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.