Editorial for TSOC '15 Contest 2 #2 - Diamonds


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

Author: BMP

Before the explanation: the problem has no tricks and no corner cases, since N is always promised to be odd. Thus if the algorithm performs correctly, you will AC all test cases.

Now, a reasonable way to solve this problem would be to have two for loops (one for the top of the diamond, the other for the bottom). To figure out how many asterisks we have to put on i^{th} line, consider how far we are in the loop. The number of asterisks can be found using the equation: height / 2 - i and the number of spaces 1 + 2 * i. This is really, all you need to do to solve this 6 point problem. Here's the code.

This is an implementation problem, thus, time shouldn't matter.

#include <iostream>

void put(char c, int t){
    for(int i = 0; i < t; i++){
        std::cout << c;
    }
}

int main(){
    int height;
    std::cin >> height;
    put('*', height);
    put('\n', 1);
    for(int i = 0; i < height / 2; i++){
        put('*', height / 2 - i);
        put(' ', 1 + 2 * i);
        put('*', height / 2 - i);
        put('\n', 1);
    }
    for(int i = height / 2 - 2; i >= 0; i--){
        put('*', height / 2 - i);
        put(' ', 1 + 2 * i);
        put('*', height / 2 - i);
        put('\n', 1);
    }
    put('*', height);
}

Comments

There are no comments at the moment.