区間&リュックサックdp練習問題問題解(AB C T)

39357 ワード

文書ディレクトリ
  • A題
  • B題
  • C題
  • T題
  • A題
    Gappu has a very busy weekend ahead of him. Because, next weekend is Halloween, and he is planning to attend as many parties as he can. Since it’s Halloween, these parties are all costume parties, Gappu always selects his costumes in such a way that it blends with his friends, that is, when he is attending the party, arranged by his comic-book-fan friends, he will go with the costume of Superman, but when the party is arranged contest-buddies, he would go with the costume of ‘Chinese Postman’.
    Since he is going to attend a number of parties on the Halloween night, and wear costumes accordingly, he will be changing his costumes a number of times. So, to make things a little easier, he may put on costumes one over another (that is he may wear the uniform for the postman, over the superman costume). Before each party he can take off some of the costumes, or wear a new one. That is, if he is wearing the Postman uniform over the Superman costume, and wants to go to a party in Superman costume, he can take off the Postman uniform, or he can wear a new Superman uniform. But, keep in mind that, Gappu doesn’t like to wear dresses without cleaning them first, so, after taking off the Postman uniform, he cannot use that again in the Halloween night, if he needs the Postman costume again, he will have to use a new one. He can take off any number of costumes, and if he takes off k of the costumes, that will be the last k ones (e.g. if he wears costume A before costume B, to take off A, first he has to remove B).
    Given the parties and the costumes, find the minimum number of costumes Gappu will need in the Halloween night.
    Input Input starts with an integer T (≤ 200), denoting the number of test cases.
    Each case starts with a line containing an integer N (1 ≤ N ≤ 100) denoting the number of parties. Next line contains N integers, where the ith integer ci (1 ≤ ci ≤ 100) denotes the costume he will be wearing in party i. He will attend party 1 first, then party 2, and so on.
    Output For each case, print the case number and the minimum number of required costumes.
    Sample Input 2 4 1 2 1 2 7 1 2 1 1 3 2 1
    Sample Output Case 1: 3 Case 2: 4
    これは先生が言った区间dpの例題です.n日に着るべき服のスタイルをあげます.毎回服を着ることができます.脱いだ服はもう使えません.少なくとも何枚の服を持ってすべての宴会に参加することができますか.
    構想:区間DP dp[i][j]は、区間iから区間jまでに必要とされる最低限の服装数を表す.i日目を考えると、後の[i+1,j]日の服がi日目と同じでなければ、dp[i][j]=dp[i+1][j]+1となる.そして区間[i+1,j]でi日目の服と同じ日を見つけ、その日までiを脱がない、つまりこの服が脱がなければdp[i][j]=dp[i+1][k-1]+dp[k][j]があり、可能な限りの最小値を取ればよい.
    コード#コード#
    #include 
    #include 
    #include 
    #include
    
    using namespace std;
    typedef long long LL;
    const int N = 1e2 + 10;
    int n, m;
    int num[N];
    int dp[N][N];
    
    int main()
    {
        int t;
        cin >> t;
        int Case = 0;
        while (t--)
        {
            cin >> n;
            for (int i = 1; i <= n; ++i)
                cin>>num[i];
            for (int i = n; i >= 1; --i)
                for (int j = i; j <= n; ++j)
                {
                    dp[i][j] = dp[i + 1][j] + 1;
                    for (int k = i + 1; k <= j; ++k)
                    {
                        if (num[k] == num[i])dp[i][j] = min(dp[i][j], dp[i + 1][k - 1] + dp[k][j]);
                    }
                }
            printf("Case %d: %d
    "
    , Case++, dp[1][n]); } }

    B題
    We give the following inductive definition of a “regular brackets” sequence:
    the empty sequence is a regular brackets sequence, if s is a regular brackets sequence, then (s) and [s] are regular brackets sequences, and if a and b are regular brackets sequences, then ab is a regular brackets sequence. no other sequence is a regular brackets sequence For instance, all of the following character sequences are regular brackets sequences:
    (), [], (()), ()[], ()[()]
    while the following character sequences are not:
    (, ], )(, ([)], ([(]
    Given a brackets sequence of characters a1a2 … an, your goal is to find the length of the longest regular brackets sequence that is a subsequence of s. That is, you wish to find the largest m such that for indices i1, i2, …, im where 1 ≤ i1 < i2 < … < im ≤ n, ai1ai2 … aim is a regular brackets sequence.
    Given the initial sequence ([([]])], the longest regular brackets subsequence is [([])].
    Input The input test file will contain multiple test cases. Each input test case consists of a single line containing only the characters (, ), [, and ]; each input test will have length between 1 and 100, inclusive. The end-of-file is marked by a line containing the word “end” and should not be processed.
    Output For each input case, the program should print the length of the longest possible regular brackets subsequence on a single line.
    Sample Input ((())) ()()() ([]]) )[)( ([][][) end
    Sample Output 6 6 4 0 6
    この問題も先生が話した区間DPの例題です.
    标题:()[]のみの文字列を与えて、最大どれだけの括弧が一致するかを聞く(一対の括弧は2を計算する)
    考え方:区間DPは古典的なスタックアプリケーションのように見えますが、それは完全に一致しているかどうかを判断します.
    dp[i][j]が区間[i,j]の最大完全一致数である場合、dp[i][j]1.境界が2つ一致すると、dp[i][j]=dp[i+1][j-1]+2が明らかになる.2.境界が一致しない場合、dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]).
    コード#コード#
    #include
    #include
    #include
    #include
    using namespace std;
    const int N = 100 + 10;
    int dp[N][N];
    char str[N];
    int main() 
    {
    	while (cin>>str + 1&&str[1] != 'e') 
    	{
    		memset(dp, 0, sizeof(dp));
    		int n = strlen(str + 1);
    		for (int len = 2; len <= n; len++) 
    		{
    			for (int i = 1; i <= n; i++) 
    			{
    				int j = i + len - 1;
    				if (j > n) 
    					continue;
    				if (str[i] == '(' && str[j] == ')' || str[i] == '[' && str[j] == ']') 
    					dp[i][j] = dp[i + 1][j - 1] + 2;
    				for (int k = i; k < j; k++) 
    					dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j]);
    			}
    		}
    		printf("%d
    "
    , dp[1][n]); } return 0; }

    C題
    The multiplication puzzle is played with a row of cards, each containing a single positive integer. During the move player takes one card out of the row and scores the number of points equal to the product of the number on the card taken and the numbers on the cards on the left and on the right of it. It is not allowed to take out the first and the last card in the row. After the final move, only two cards are left in the row.
    The goal is to take cards in such order as to minimize the total number of scored points.
    For example, if cards in the row contain numbers 10 1 50 20 5, player might take a card with 1, then 20 and 50, scoring 10150 + 50205 + 10505 = 500+5000+2500 = 8000
    If he would take the cards in the opposite order, i.e. 50, then 20, then 1, the score would be 15020 + 1205 + 1015 = 1000+100+50 = 1150.
    Input The first line of the input contains the number of cards N (3 <= N <= 100). The second line contains N integers in the range from 1 to 100, separated by spaces.
    Output Output must contain a single integer - the minimal score.
    Sample Input 6 10 1 50 50 20 5
    Sample Output 3650
    先生が話した例題
    題意:1つの数字を削除するたびに(最初と最後の数字は削除できません)、1つの数字を削除して得られる点数は隣接する2つの数字と彼自身の3つの数の積で、最終的には最初と最後の2つの数字が残ります.得られる最小点数はいくらですか?
    構想
    定義状態dp[i][j]:i番目からj番目までの中間の数字を全て取り出すことで得られる最小分数を区間(i,j)で最後に取られる数字をk番目に列挙すると、遷移方程式dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]+a[i]a[k]a[j])
    コード:
    #include
    #include
    #include
    #include
    using namespace std;
    const int maxn = 110;
    int n, a[maxn], dp[maxn][maxn];
    
    int main()
    {
        while (scanf("%d", &n) != EOF)
        {
            for (int i = 1; i <= n; i++) 
                scanf("%d", &a[i]);
            memset(dp, 0x3f, sizeof(dp));
            for (int l = 2; l < n; l++)
            {
                for (int i = 1; i <= n - l; i++)
                {
                    int j = i + l;
                    for (int k = i + 1; k <= j - 1; k++)
                    {
                        int tmp = a[i] * a[j] * a[k];
                        if (k > i + 1) tmp += dp[i][k];
                        if (j > k + 1) tmp += dp[k][j];
                        dp[i][j] = min(dp[i][j], tmp);
                    }
                }
            }
            printf("%d
    "
    , dp[1][n]); } return 0; }

    T題
    Before ACM can do anything, a budget must be prepared and the necessary financial support obtained. The main income for this action comes from Irreversibly Bound Money (IBM). The idea behind is simple. Whenever some ACM member has any small money, he takes all the coins and throws them into a piggy-bank. You know that this process is irreversible, the coins cannot be removed without breaking the pig. After a sufficiently long time, there should be enough cash in the piggy-bank to pay everything that needs to be paid.
    But there is a big problem with piggy-banks. It is not possible to determine how much money is inside. So we might break the pig into pieces only to find out that there is not enough money. Clearly, we want to avoid this unpleasant situation. The only possibility is to weigh the piggy-bank and try to guess how many coins are inside. Assume that we are able to determine the weight of the pig exactly and that we know the weights of all coins of a given currency. Then there is some minimum amount of money in the piggy-bank that we can guarantee. Your task is to find out this worst case and determine the minimum amount of cash inside the piggy-bank. We need your help. No more prematurely broken pigs!
    Input The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing two integers E and F. They indicate the weight of an empty pig and of the pig filled with coins. Both weights are given in grams. No pig will weigh more than 10 kg, that means 1 <= E <= F <= 10000. On the second line of each test case, there is an integer number N (1 <= N <= 500) that gives the number of various coins used in the given currency. Following this are exactly N lines, each specifying one coin type. These lines contain two integers each, Pand W (1 <= P <= 50000, 1 <= W <=10000). P is the value of the coin in monetary units, W is it’s weight in grams. Output
    Print exactly one line of output for each test case. The line must contain the sentence “The minimum amount of money in the piggy-bank is X.” where X is the minimum amount of money that can be achieved using coins with the given total weight. If the weight cannot be reached exactly, print a line “This is impossible.”.
    Sample Input 3 10 110 2 1 1 30 50 10 110 2 1 1 50 30 1 6 2 10 3 20 4
    Sample Output The minimum amount of money in the piggy-bank is 60. The minimum amount of money in the piggy-bank is 100. This is impossible.
    先生の例題
    構想:とても基本的な完全なリュックサックの問題、直接書くのはokで、注意は最小を求めるのです
    コード#コード#
    #include 
    #include 
    #include 
    #include
    using namespace std;
    const int MAX_N = 1000003;
    int v[MAX_N], w[MAX_N], dp[MAX_N];
    int main() 
    {
        int n, E, F, N, i, j, W;
        cin >> n;
        while (n--) 
        {
            cin >> E >> F;
            cin >> N;
            W = F - E;
            memset(v, 0, sizeof(v));
            memset(w, 0, sizeof(w));
            for (i = 1; i <= W; i++) 
                dp[i] = MAX_N;
            dp[0] = 0;
            for (i = 1; i <= N; i++) 
                cin >> v[i] >> w[i];
            for (i = 1; i <= N; i++)
                for (j = w[i]; j <= W; j++) 
                    dp[j] = min(dp[j], dp[j - w[i]] + v[i]);
            if (dp[W] != MAX_N) 
                cout << "The minimum amount of money in the piggy-bank is " << dp[W] << "." << endl;
            else 
                cout << "This is impossible." << endl;
        }
        return 0;
    }