Waterloo Cup algorithm to improve the use of candy (Java) __ algorithm

Source: Internet
Author: User

According to the sample input, the starting candy number is 15, after the first time to take away 1 sugars, mother will also take 1 sugars, the problem

It becomes the maximum number of sugars that can be obtained at the start of only 13 sugars, and if little B takes 1 sugars, the mother will take 1 more.

The problem becomes the maximum number of sugars that can be obtained in 11 sugars ... It is obvious that the child problem (the new problem) is not independent of each other,

Dynamic programming should be used to solve problems:

write out the state transition equation by topic: Dp[i] = max{Dp[i], dp[i–temp * 2] + temp};

Dp[i] Show in Candy for I time, small B The maximum number of sweets that can be obtained .

Temp Show in Candy for I time, small B and the number of sweets that MOM can take. . The problem is solved by writing out the state transition equation and implementing the code as follows:

import java.util.Scanner; import java.util.Vector;

	public class main{static int[] dp = new INT[100001];
		public static void Main (string[] args) {Scanner scan = new Scanner (system.in);

		int n = scan.nextint ();
			The implementation of the dynamic transformation equation for (int i=0; i<=n; i++) {vector<integer> VEC = f (i);
			int len = Vec.size ();
			for (int j=0; j<len; J + +) {Dp[i] = Math.max (dp[i), Dp[i-2*vec.get (j)]+vec.get (j));
	} System.out.println (Dp[n]);  //Get all the decomposition of num below the root number, and use the collection Vector to store the public static vector<integer> f (int num) {vector<integer> VEC =
		New Vector<integer> ();
			for (int i=2 i * i<=num; i++) {if (num% i = = 0) {vec.add (i);
	} return VEC; }
}

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.