Ural 1005 Stone Pile

Source: Internet
Author: User

This is the question of the 01 backpack. Although the backpack won't, I still can see it. The recursive formula was not written. Later I learned it together as a DFS, so I started,

The question is to give you n stones whose weight is wn so that you can put them in two packages to see that the difference between the two is the minimum and the difference is output.

DFS code

# Include <stdio. h> int sum; int h, T; int A [1, 100]; void DFS (int x, int y) {If (x = T) {If (Y> H) H = y; return;} If (H = sum/2) return; If (Y + A [x] <= sum/2) // The equals sign must exist, this has been called for a long time, because they may be equal. DFS (x + 1, Y + A [x]); DFS (x + 1, Y);} int main () {While (scanf ("% d ", & T) = 1) {sum = 0; h = 0; For (INT I = 0; I <t; I ++) {scanf ("% d ", & A [I]); sum + = A [I];} // printf ("% d \ n", sum); DFS (0, 0 ); // printf ("% d \ n", H); printf ("% d \ n", Sum-2 * H );}}
DP code
# Include <cstring> # include <cstdio> const int Maxx = 2000010; int DP [Maxx], a [25], n; int ABS (int x) {return (x> 0 )? X:-X;} int Maxxx (int A, int B) {return (A> B )? A: B;} int main () {While (scanf ("% d", & n) = 1) {If (n = 1) {scanf ("% d", & A [0]); printf ("% d", a [0]); continue;} int sum = 0, temp, ans; for (INT I = 1; I <= N; I ++) {scanf ("% d", & A [I]); sum + = A [I]; DP [I] = 0;} temp = sum/2; DP [0] = 0; For (INT I = 1; I <= N; I ++) for (Int J = temp; j> = A [I]; j --) DP [J] = Maxxx (DP [J-A [I] + A [I], DP [J]); // you can find the maximum number in [0-temp] For (INT I = temp; I> = 0; I --) if (DP [I]! = 0) {ans = DP [I]; break;} printf ("% d \ n", ABS (Sum-2 * ans);} return 0 ;}


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.