UV 6177 The King's Ups and Downs

Source: Internet
Author: User

The question is how many values in the full arrangement of 1-N are displayed in the descending or descending order.

This sort is called alternating permutations or Extremal Permutations.

You can use DP.

Dp (n, k) indicates that the length is n, the last number is k, and the last two numbers are incremental;

Dp2 (n, k) indicates that the length is n, the last number is k, and the last two numbers are in descending order;

So:

Dp (n, k) = dp2 (n, n + 1-k );

For example, 132 (low) is equivalent to 312 (high), and the relative position is equal to 4.

We will consider the last digit of dp [n] [k] as follows:

The last digit is k, because the last two digits of dp [n] [k] are incremental, so the maximum value of the nth digit is K-1. We can easily derive the DP equation:

 
 


Also:

 

So: dp (n, k) = dp (n-1, n + 1-k) + dp (n, k-1 );

The boundary condition is omitted.

Code:


[Cpp]
# Include <iostream>
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
Using namespace std;
 
# Define Maxn 25
# Define LL long
LL dp [Maxn] [Maxn];
LL ans [Maxn];
 
 
Void init ()
{
Memset (dp, 0, sizeof (dp ));
Memset (ans, 0, sizeof (ans ));
Dp [1] [1] = 1;
Ans [1] = 1;
For (int I = 2; I <= 20; I ++)
{
For (int k = 2; k <= I; k ++)
{
Dp [I] [k] = dp [I-1] [I + 1-k] + dp [I] [k-1];
Ans [I] + = dp [I] [k];
}
Ans [I] * = 2;
// Printf ("% lld \ n", ans [I]);
}
}
Int main ()
{
# Ifndef ONLINE_JUDGE
Freopen ("in.txt", "r", stdin );
# Endif
Init ();
Int p;
Int m, n;
Scanf ("% d", & p );
While (p --)
{
Scanf ("% d", & m, & n );
Printf ("% d % lld \ n", m, ans [n]);
}
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.