4月 02, 2009

【解題】Triangle Wave

@
ACM Volume IV 488 - Triangle Wave


The Problem

In this problem you are to generate a triangular wave form according to a specified pair of Amplitude and Frequency.


Input and Output

The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.

Each input set will contain two integers, each on a separate line. The first integer is the Amplitude; the second integer is the Frequency.

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.

For the output of your program, you will be printing wave forms each separated by a blank line. The total number of wave forms equals the Frequency, and the horizontal ``height'' of each wave equals the Amplitude. The Amplitude will never be greater than nine.

The waveform itself should be filled with integers on each line which indicate the ``height'' of that line.

NOTE: There is a blank line after each separate waveform, excluding the last one.


Sample Input

1

3
2


Sample Output

1
22
333
22
1

1
22
333
22
1


解題思考

  這一題本身不難,不過我的上傳卻不斷地 Time limit exceeded。


  我的方法是,分別建立每一行要印出的字串。由於波浪的每一行都是相同的個位數字,所以我可以直接利用 memset() 函式,快速建立每一行要印出的字串。

  接著,我將每一行字串直接組成一個「波浪字串」之後,再根據頻率重複印出字串,就達到題目的要求了。


參考解答(C++)

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    int n;
    cin >> n;

    bool first = true;
    for (int i = 0; i < n; i++)
    {
        int a, f;
        cin >> a >> f;

        string wave;
        char number[10];

        // 畫出上波浪
        for (int j = 1; j < a; j++)
        {
            memset(number, (j + '0'), j);
            number[j] = '\0';

            wave += number;
            wave += '\n';
        }

        // 畫出下波浪
        for (int j = a; j > 0; j--)
        {
            memset(number, (j + '0'), j);
            number[j] = '\0';

            wave += number;
            wave += '\n';
        }

        for (int j = 0; j < f; j++)
        {
            // 判別是否該換行
            if (first)  { first = false; }
            else        { cout << endl; }

            // 輸出波浪
            cout << wave;
        }
    }

#ifndef ONLINE_JUDGE
    system("pause");
#endif

    return 0;
}

0 回覆:

張貼留言