Ultraviolet A 116-Unidirectional TSP

Source: Internet
Author: User

Question: Calculate the sum and minimum of a path from left to right. Each time, you can use the cai method to obtain the rows, uplink and downlink.
Analysis: dp. The number column is deformed. Because the minimum sequence is required, the smallest sequence can be taken from the right to the left dp, which can ensure that the right is the smallest sequence. Each time the subsequent node is recorded, the output is enough.

Note: At the top and bottom two rows, numbers may be programmed in the largest and smallest rows.

[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
 
Int mat [12] [1, 102] = {0 };
Int sum [12] [1, 102] = {0 };
Int chi [12] [1, 102] = {0 };
 
Void output (int r, int c, int m)
{
If (c <m ){
Printf ("% d", r );
Output (chi [r] [c], c + 1, m );
} Else {
Printf ("% d \ n", r );
}
}
 
Int main ()
{
Int n, m;
While (scanf ("% d", & n, & m )! = EOF ){
Memset (sum, 0, sizeof (sum ));
For (int I = 1; I <= n; ++ I)
For (int j = 1; j <= m; ++ j ){
Scanf ("% d", & mat [I] [j]);
}

For (int I = m; I> = 1; -- I)
For (int j = 1; j <= n; ++ j ){
Sum [j] [I] = sum [j] [I + 1] + mat [j] [I];
Chi [j] [I] = j;
Int down = j + 1;
If (down> n) down = 1;
If (sum [j] [I] = sum [down] [I + 1] + mat [j] [I]) {
Sum [j] [I] = sum [down] [I + 1] + mat [j] [I];
If (chi [j] [I]> down)
Chi [j] [I] = down;
}
If (sum [j] [I]> sum [down] [I + 1] + mat [j] [I]) {
Sum [j] [I] = sum [down] [I + 1] + mat [j] [I];
Chi [j] [I] = down;
}
Int up = J-1;
If (up <1) up = n;
If (sum [j] [I] = sum [up] [I + 1] + mat [j] [I]) {
Sum [j] [I] = sum [up] [I + 1] + mat [j] [I];
If (chi [j] [I]> up)
Chi [j] [I] = up;
}
If (sum [j] [I]> sum [up] [I + 1] + mat [j] [I]) {
Sum [j] [I] = sum [up] [I + 1] + mat [j] [I];
Chi [j] [I] = up;
}
}
Int minv = 0x7ffffff, space = 1;
For (int I = 1; I <= n; ++ I)
If (minv> sum [I] [1]) {
Minv = sum [I] [1];
Space = I;
}

Output (space, 1, m );
Printf ("% d \ n", minv );
}
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.