Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.50/6: Рейтинг темы: голосов - 6, средняя оценка - 4.50
0 / 0 / 0
Регистрация: 30.07.2012
Сообщений: 38

Как вы тестируете время выполнения программы?

05.12.2013, 21:01. Показов 1297. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый день.

Вопрос к олимпиадникам: как вы тестируете время выполнения ваших программ во время подготовки? Есть какая-нибудь задача и написано: "Время выполнения 0.5 секунд" - это на их сервере. А сколько это на моем компьютере, как узнать?

Вся соль в том, что а алгоритме я почти уверен, вопрос в реализации. Как тестирую я:
я внимательно смотрю на код и пытаюсь понять, что можно выкинуть (функцию, массив и пр). Затем я начинаю менять типы: вроде говорят что unsigned int работает быстрее,чем int. И т. д. Почти всегда это не приносит должного эффекта, а зачастую бывает даже хуже. К тому когда решение таки найдено, я получаю очень большое количество не правильных попыток, что не приятно.

Вот сейчас у меня выполнение 0,503 секунд. И я уже не знаю что там можно еще выкинуть.
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
05.12.2013, 21:01
Ответы с готовыми решениями:

Как уменьшить время выполнения программы?
Помогите пожалуйста сократить время выполнения программы. Работает за 5.008 сек, а должна за 1 сек. Вот код: #include...

Как зафиксировать время начала выполнения программы?
Доброго времени суток, форумчане! у меня два вопроса: 1. как зафиксировать время начала выполнения программы? 2. как зафиксировать...

Как зафиксировать время начала выполнения программы
Здравствуйте) подскажите, пожалуйста, как зафиксировать время начала выполнения программы и текущее время в C++ Builder?

4
Мой лучший друг-отладчик!
 Аватар для ZaMaZaN4iK
167 / 167 / 30
Регистрация: 24.06.2012
Сообщений: 662
Записей в блоге: 5
05.12.2013, 21:04
R_e_n, кинь исходник плиз
0
0 / 0 / 0
Регистрация: 30.07.2012
Сообщений: 38
05.12.2013, 21:34  [ТС]
Цитата Сообщение от ZaMaZaN4iK Посмотреть сообщение
R_e_n, кинь исходник плиз
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#include <iostream>
#include <vector>
 
 
class BinaryTree {
private:
    // index is number of node
    std::vector<unsigned int> keys;
    std::vector<unsigned int> left_child_pos;
    std::vector<unsigned int> right_child_pos;
    std::vector<unsigned int> parent_positions;
    size_t size;
 
    inline size_t right_go_up(size_t position);
    inline size_t find_left_most(size_t position);
 
public:
    BinaryTree(unsigned int root_key, size_t node_numbers);
    int insert(unsigned int key);
    int insert_correct(unsigned int key);
    inline size_t get_size();
    int pre_order_traversal(size_t position);
    int in_order_traversal(size_t position);
    int post_order_traversal(size_t position);
};
 
const unsigned int EMPTY_POSITION = static_cast<unsigned int>(-1);
 
BinaryTree::BinaryTree(unsigned int root_key, size_t node_numbers) {
    this->keys.resize(node_numbers);
    this->left_child_pos.resize(node_numbers, EMPTY_POSITION);
    this->right_child_pos.resize(node_numbers, EMPTY_POSITION);
    this->parent_positions.resize(node_numbers, EMPTY_POSITION);
    
    this->keys[0] = root_key;
    this->size = 1;
}
 
int BinaryTree::insert(unsigned int key) {
 
    if (key < this->keys[this->size - 1]) {
        this->keys[this->size] = key;
        this->left_child_pos[this->size - 1] = this->size;
        this->parent_positions[this->size] = this->size - 1;
        ++this->size;
    }
    else
    {
        size_t position = this->size - 1;
        size_t parent_position = this->parent_positions[position];
        if (parent_position != EMPTY_POSITION && 
            this->keys[position] <= key && this->keys[parent_position] <= key) {
 
                while (parent_position != EMPTY_POSITION && 
                    this->keys[position] <= key && this->keys[parent_position] <= key) {
            
                        position = this->parent_positions[position];
                        parent_position = this->parent_positions[position];
                }
 
                if (this->right_child_pos[position] != EMPTY_POSITION) {
 
                    while (this->right_child_pos[position] != EMPTY_POSITION && 
                        position < this->right_child_pos.size()) {
                        
                            position = this->right_child_pos[position];
                    }
                }
                this->keys[this->size] = key;
                this->right_child_pos[position] = this->size;
                this->parent_positions[this->size] = position;
                ++this->size;
        }
        // втавляем справа от текущей вершины
        else
        {
            this->keys[this->size] = key;
            this->right_child_pos[position] = this->size;
            this->parent_positions[this->size] = position;
            ++this->size;
        }
    }
 
    return 0;
}
 
 
int BinaryTree::insert_correct(unsigned int key) {
 
    if (key < this->keys[this->size - 1]) {
        this->keys[this->size] = key;
        this->left_child_pos[this->size - 1] = this->size;
        this->parent_positions[this->size] = this->size - 1;
        ++this->size;
    }
    else
    {
        size_t position = 0;
        bool found = false;
        while (!found) {
            if (key < this->keys[position]) {
                if (this->left_child_pos[position] == EMPTY_POSITION) {
                    this->keys[this->size] = key;
                    this->left_child_pos[position] = this->size;
                    this->parent_positions[this->size] = position;
                    ++this->size;
                    found = true;
                }
                else
                {
                    position = this->left_child_pos[position];
                }
            }
            else
            {
                if (this->right_child_pos[position] == EMPTY_POSITION) {
                    this->keys[this->size] = key;
                    this->right_child_pos[position] = this->size;
                    this->parent_positions[this->size] = position;
                    ++this->size;
                    found = true;
                }
                else
                {
                    position = this->right_child_pos[position];
                }
            }
        }
    }
 
    return 0;
}
 
inline size_t BinaryTree::get_size() {
    return this->size;
}
 
inline size_t BinaryTree::find_left_most(size_t position) {
    while (position != EMPTY_POSITION && this->left_child_pos[position] != EMPTY_POSITION) {
        position = this->left_child_pos[position];
    }
    return position;
}
 
inline size_t BinaryTree::right_go_up(size_t position) {
    size_t parent_position = this->parent_positions[position];
    while (position != EMPTY_POSITION && parent_position != EMPTY_POSITION &&
        this->right_child_pos[parent_position ] == position) {
 
            position = parent_position;
            parent_position = this->parent_positions[position];
    }
    if (position == 0) {
        return position;    
    }
    else
    {
        return parent_position;
    }
}
 
int BinaryTree::in_order_traversal(size_t position) {
 
    size_t parent_position;
    size_t root_count = 0;
 
    position = this->find_left_most(position);
    if (position == 0) {
        ++root_count;
        if (root_count == 2) {
            return 0;
        }
    }
 
    while (position != EMPTY_POSITION) {
        std::cout << this->keys[position] << " ";
 
        if (this->right_child_pos[position] != EMPTY_POSITION) {
            position = this->find_left_most(this->right_child_pos[position]);
        }
        else
        {
            parent_position = this->parent_positions[position];
            if (parent_position != EMPTY_POSITION && 
                this->right_child_pos[parent_position] == position) {
                
                    position = this->right_go_up(position);
            }
            else
            {
                position = parent_position;
            }
        }
        if (position == 0) {
            ++root_count;
            if (root_count == 2) {
                return 0;
            }
        }
    }
 
    return 0;
}
 
int BinaryTree::post_order_traversal(size_t position) {
 
    std::vector<size_t> positions;
    positions.reserve(this->keys.size());
    std::vector<unsigned int> post_order_keys;
    post_order_keys.reserve(this->keys.size());
    positions.push_back(position);
 
    while (!positions.empty()) {
        
        position = positions[positions.size() - 1];
        positions.pop_back();
        post_order_keys.push_back(this->keys[position]);
 
        if (position != EMPTY_POSITION) {
            if (this->left_child_pos[position] != EMPTY_POSITION) {
                positions.push_back(this->left_child_pos[position]);
            }
            if (this->right_child_pos[position] != EMPTY_POSITION) {
                positions.push_back(this->right_child_pos[position]);
            }
        }
    }
 
    while (!post_order_keys.empty()) {
        std::cout << post_order_keys[post_order_keys.size() - 1] << " ";
        post_order_keys.pop_back();
    }
    
    return 0;
}
 
int main() {
 
    std::ios_base::sync_with_stdio(false);
 
    size_t keys_number;
    std::cin >> keys_number;
 
    unsigned int key;
    std::cin >> key;
    BinaryTree binary_tree(key, keys_number);
 
    for (size_t keys_index = 1; keys_index < keys_number; ++keys_index) {
        std::cin >> key;
        binary_tree.insert(key);
    }
    
    binary_tree.post_order_traversal(0);
    std::cout << "\n";
 
    binary_tree.in_order_traversal(0);
    std::cout << "\n";
 
    return 0;
}
Тут классы, но когда я переписал без классов стало только хуже.

На всякий случай выложу само задание:

Во входе задано бинарное дерево поиска, такое что для любой вершины все ключи в ее левом поддереве строго меньше ее ключа, а все ключи в ее правом поддереве не меньше ее ключа. В первой строке количество вершин в дереве, во второй ключи дерева в порядке preorder. В выход выведите две строки. В первой дерево в порядке postorder, во второй дерево в порядке inorder. Количество вершин дерева не более 100 000. Значения ключей от 0 до 1 000 000 000.

Добавлено через 2 минуты
Что то какой то большой код получился.

и еще
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#include <iostream>
#include <vector>
 
 
const unsigned int EMPTY_POSITION = static_cast<unsigned int>(-1);
std::vector<unsigned int> keys;
std::vector<unsigned int> left_child_pos;
std::vector<unsigned int> right_child_pos;
std::vector<unsigned int> parent_positions;
 
inline int post_order_traversal(size_t position) {
 
    if (position != EMPTY_POSITION) {
        if (left_child_pos[position] != EMPTY_POSITION) {
            post_order_traversal(left_child_pos[position]);
        }
        if (right_child_pos[position] != EMPTY_POSITION) {
            post_order_traversal(right_child_pos[position]);
        }
        std::cout << keys[position] << " ";
    }
 
    return 0;
}
 
inline size_t find_left_most(size_t position) {
    while (position != EMPTY_POSITION && left_child_pos[position] != EMPTY_POSITION) {
        position = left_child_pos[position];
    }
    return position;
}
 
inline size_t right_go_up(size_t position) {
    size_t parent_position = parent_positions[position];
    while (position != EMPTY_POSITION && parent_position != EMPTY_POSITION &&
        right_child_pos[parent_position ] == position) {
 
            position = parent_position;
            parent_position = parent_positions[position];
    }
    if (position == 0) {
        return position;    
    }
    else
    {
        return parent_position;
    }
}
 
int main() {
 
    std::ios_base::sync_with_stdio(false);
 
    unsigned int keys_number;
    std::cin >> keys_number;
 
    keys.resize(keys_number);
    left_child_pos.resize(keys_number, EMPTY_POSITION);
    right_child_pos.resize(keys_number, EMPTY_POSITION);
    parent_positions.resize(keys_number, EMPTY_POSITION);
 
    
    unsigned int key;
    std::cin >> key;
 
    keys[0] = key;
    unsigned int size;
    size = 1;
 
    for (size_t keys_index = 1; keys_index < keys_number; ++keys_index) {
        std::cin >> key;
 
        if (key < keys[size - 1]) {
            keys[size] = key;
            left_child_pos[size - 1] = size;
            parent_positions[size] = size - 1;
            ++size;
        }
        else
        {
            size_t position = 0;
            bool found = false;
            while (!found) {
                if (key < keys[position]) {
                    if (left_child_pos[position] == EMPTY_POSITION) {
                        keys[size] = key;
                        left_child_pos[position] = size;
                        parent_positions[size] = position;
                        ++size;
                        found = true;
                    }
                    else
                    {
                        position = left_child_pos[position];
                    }
                }
                else
                {
                    if (right_child_pos[position] == EMPTY_POSITION) {
                        keys[size] = key;
                        right_child_pos[position] = size;
                        parent_positions[size] = position;
                        ++size;
                        found = true;
                    }
                    else
                    {
                        position = right_child_pos[position];
                    }
                }
            }
        }
    }
 
    // post_order
    size_t position = 0;
    std::vector<size_t> positions;
    std::vector<unsigned int> post_order_keys;
    positions.push_back(position);
 
    while (!positions.empty()) {
        
        position = positions[positions.size() - 1];
        positions.pop_back();
        post_order_keys.push_back(keys[position]);
 
        if (position != EMPTY_POSITION) {
            if (left_child_pos[position] != EMPTY_POSITION) {
                positions.push_back(left_child_pos[position]);
            }
            if (right_child_pos[position] != EMPTY_POSITION) {
                positions.push_back(right_child_pos[position]);
            }
        }
    }
 
    while (!post_order_keys.empty()) {
        std::cout << post_order_keys.at(post_order_keys.size() - 1) << " ";
        post_order_keys.pop_back();
    }
    std::cout << "\n";
 
    // in_order
    position = 0;
    size_t parent_position;
    size_t root_count = 0;
 
    position = find_left_most(position);
    if (position == 0) {
        ++root_count;
        if (root_count == 2) {
            std::cout << "\n";
            return 0;
        }
    }
 
    while (position != EMPTY_POSITION) {
        std::cout << keys[position] << " ";
 
        if (right_child_pos[position] != EMPTY_POSITION) {
            position = find_left_most(right_child_pos[position]);
        }
        else
        {
            parent_position = parent_positions[position];
            if (parent_position != EMPTY_POSITION && 
                right_child_pos[parent_position] == position) {
                
                    position = right_go_up(position);
            }
            else
            {
                position = parent_position;
            }
        }
        if (position == 0) {
            ++root_count;
            if (root_count == 2) {
                std::cout << "\n";
                return 0;
            }
        }
    }
    std::cout << "\n";
 
    return 0;
}
Вот так я попытался выкинуть классы, стало 0,551:-(

Добавлено через 3 минуты
Может не стоит в таких случаях колдунствовать, искать ошибку в алгоритме?

Добавлено через 18 минут
Цитата Сообщение от R_e_n Посмотреть сообщение
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#include <iostream>
#include <vector>
 
 
class BinaryTree {
private:
    // index is number of node
    std::vector<unsigned int> keys;
    std::vector<unsigned int> left_child_pos;
    std::vector<unsigned int> right_child_pos;
    std::vector<unsigned int> parent_positions;
    size_t size;
 
    inline size_t right_go_up(size_t position);
    inline size_t find_left_most(size_t position);
 
public:
    BinaryTree(unsigned int root_key, size_t node_numbers);
    int insert(unsigned int key);
    int insert_correct(unsigned int key);
    inline size_t get_size();
    int pre_order_traversal(size_t position);
    int in_order_traversal(size_t position);
    int post_order_traversal(size_t position);
};
 
const unsigned int EMPTY_POSITION = static_cast<unsigned int>(-1);
 
BinaryTree::BinaryTree(unsigned int root_key, size_t node_numbers) {
    this->keys.resize(node_numbers);
    this->left_child_pos.resize(node_numbers, EMPTY_POSITION);
    this->right_child_pos.resize(node_numbers, EMPTY_POSITION);
    this->parent_positions.resize(node_numbers, EMPTY_POSITION);
    
    this->keys[0] = root_key;
    this->size = 1;
}
 
int BinaryTree::insert(unsigned int key) {
 
    if (key < this->keys[this->size - 1]) {
        this->keys[this->size] = key;
        this->left_child_pos[this->size - 1] = this->size;
        this->parent_positions[this->size] = this->size - 1;
        ++this->size;
    }
    else
    {
        size_t position = this->size - 1;
        size_t parent_position = this->parent_positions[position];
        if (parent_position != EMPTY_POSITION && 
            this->keys[position] <= key && this->keys[parent_position] <= key) {
 
                while (parent_position != EMPTY_POSITION && 
                    this->keys[position] <= key && this->keys[parent_position] <= key) {
            
                        position = this->parent_positions[position];
                        parent_position = this->parent_positions[position];
                }
 
                if (this->right_child_pos[position] != EMPTY_POSITION) {
 
                    while (this->right_child_pos[position] != EMPTY_POSITION && 
                        position < this->right_child_pos.size()) {
                        
                            position = this->right_child_pos[position];
                    }
                }
                this->keys[this->size] = key;
                this->right_child_pos[position] = this->size;
                this->parent_positions[this->size] = position;
                ++this->size;
        }
        // втавляем справа от текущей вершины
        else
        {
            this->keys[this->size] = key;
            this->right_child_pos[position] = this->size;
            this->parent_positions[this->size] = position;
            ++this->size;
        }
    }
 
    return 0;
}
 
 
int BinaryTree::insert_correct(unsigned int key) {
 
    if (key < this->keys[this->size - 1]) {
        this->keys[this->size] = key;
        this->left_child_pos[this->size - 1] = this->size;
        this->parent_positions[this->size] = this->size - 1;
        ++this->size;
    }
    else
    {
        size_t position = 0;
        bool found = false;
        while (!found) {
            if (key < this->keys[position]) {
                if (this->left_child_pos[position] == EMPTY_POSITION) {
                    this->keys[this->size] = key;
                    this->left_child_pos[position] = this->size;
                    this->parent_positions[this->size] = position;
                    ++this->size;
                    found = true;
                }
                else
                {
                    position = this->left_child_pos[position];
                }
            }
            else
            {
                if (this->right_child_pos[position] == EMPTY_POSITION) {
                    this->keys[this->size] = key;
                    this->right_child_pos[position] = this->size;
                    this->parent_positions[this->size] = position;
                    ++this->size;
                    found = true;
                }
                else
                {
                    position = this->right_child_pos[position];
                }
            }
        }
    }
 
    return 0;
}
 
inline size_t BinaryTree::get_size() {
    return this->size;
}
 
inline size_t BinaryTree::find_left_most(size_t position) {
    while (position != EMPTY_POSITION && this->left_child_pos[position] != EMPTY_POSITION) {
        position = this->left_child_pos[position];
    }
    return position;
}
 
inline size_t BinaryTree::right_go_up(size_t position) {
    size_t parent_position = this->parent_positions[position];
    while (position != EMPTY_POSITION && parent_position != EMPTY_POSITION &&
        this->right_child_pos[parent_position ] == position) {
 
            position = parent_position;
            parent_position = this->parent_positions[position];
    }
    if (position == 0) {
        return position;    
    }
    else
    {
        return parent_position;
    }
}
 
int BinaryTree::in_order_traversal(size_t position) {
 
    size_t parent_position;
    size_t root_count = 0;
 
    position = this->find_left_most(position);
    if (position == 0) {
        ++root_count;
        if (root_count == 2) {
            return 0;
        }
    }
 
    while (position != EMPTY_POSITION) {
        std::cout << this->keys[position] << " ";
 
        if (this->right_child_pos[position] != EMPTY_POSITION) {
            position = this->find_left_most(this->right_child_pos[position]);
        }
        else
        {
            parent_position = this->parent_positions[position];
            if (parent_position != EMPTY_POSITION && 
                this->right_child_pos[parent_position] == position) {
                
                    position = this->right_go_up(position);
            }
            else
            {
                position = parent_position;
            }
        }
        if (position == 0) {
            ++root_count;
            if (root_count == 2) {
                return 0;
            }
        }
    }
 
    return 0;
}
 
int BinaryTree::post_order_traversal(size_t position) {
 
    std::vector<size_t> positions;
    positions.reserve(this->keys.size());
    std::vector<unsigned int> post_order_keys;
    post_order_keys.reserve(this->keys.size());
    positions.push_back(position);
 
    while (!positions.empty()) {
        
        position = positions[positions.size() - 1];
        positions.pop_back();
        post_order_keys.push_back(this->keys[position]);
 
        if (position != EMPTY_POSITION) {
            if (this->left_child_pos[position] != EMPTY_POSITION) {
                positions.push_back(this->left_child_pos[position]);
            }
            if (this->right_child_pos[position] != EMPTY_POSITION) {
                positions.push_back(this->right_child_pos[position]);
            }
        }
    }
 
    while (!post_order_keys.empty()) {
        std::cout << post_order_keys[post_order_keys.size() - 1] << " ";
        post_order_keys.pop_back();
    }
    
    return 0;
}
 
int main() {
 
    std::ios_base::sync_with_stdio(false);
 
    size_t keys_number;
    std::cin >> keys_number;
 
    unsigned int key;
    std::cin >> key;
    BinaryTree binary_tree(key, keys_number);
 
    for (size_t keys_index = 1; keys_index < keys_number; ++keys_index) {
        std::cin >> key;
        binary_tree.insert(key);
    }
    
    binary_tree.post_order_traversal(0);
    std::cout << "\n";
 
    binary_tree.in_order_traversal(0);
    std::cout << "\n";
 
    return 0;
}
Тут классы, но когда я переписал без классов стало только хуже.

На всякий случай выложу само задание:

Во входе задано бинарное дерево поиска, такое что для любой вершины все ключи в ее левом поддереве строго меньше ее ключа, а все ключи в ее правом поддереве не меньше ее ключа. В первой строке количество вершин в дереве, во второй ключи дерева в порядке preorder. В выход выведите две строки. В первой дерево в порядке postorder, во второй дерево в порядке inorder. Количество вершин дерева не более 100 000. Значения ключей от 0 до 1 000 000 000.

Добавлено через 2 минуты
Что то какой то большой код получился.

и еще
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#include <iostream>
#include <vector>
 
 
const unsigned int EMPTY_POSITION = static_cast<unsigned int>(-1);
std::vector<unsigned int> keys;
std::vector<unsigned int> left_child_pos;
std::vector<unsigned int> right_child_pos;
std::vector<unsigned int> parent_positions;
 
inline int post_order_traversal(size_t position) {
 
    if (position != EMPTY_POSITION) {
        if (left_child_pos[position] != EMPTY_POSITION) {
            post_order_traversal(left_child_pos[position]);
        }
        if (right_child_pos[position] != EMPTY_POSITION) {
            post_order_traversal(right_child_pos[position]);
        }
        std::cout << keys[position] << " ";
    }
 
    return 0;
}
 
inline size_t find_left_most(size_t position) {
    while (position != EMPTY_POSITION && left_child_pos[position] != EMPTY_POSITION) {
        position = left_child_pos[position];
    }
    return position;
}
 
inline size_t right_go_up(size_t position) {
    size_t parent_position = parent_positions[position];
    while (position != EMPTY_POSITION && parent_position != EMPTY_POSITION &&
        right_child_pos[parent_position ] == position) {
 
            position = parent_position;
            parent_position = parent_positions[position];
    }
    if (position == 0) {
        return position;    
    }
    else
    {
        return parent_position;
    }
}
 
int main() {
 
    std::ios_base::sync_with_stdio(false);
 
    unsigned int keys_number;
    std::cin >> keys_number;
 
    keys.resize(keys_number);
    left_child_pos.resize(keys_number, EMPTY_POSITION);
    right_child_pos.resize(keys_number, EMPTY_POSITION);
    parent_positions.resize(keys_number, EMPTY_POSITION);
 
    
    unsigned int key;
    std::cin >> key;
 
    keys[0] = key;
    unsigned int size;
    size = 1;
 
    for (size_t keys_index = 1; keys_index < keys_number; ++keys_index) {
        std::cin >> key;
 
        if (key < keys[size - 1]) {
            keys[size] = key;
            left_child_pos[size - 1] = size;
            parent_positions[size] = size - 1;
            ++size;
        }
        else
        {
            size_t position = 0;
            bool found = false;
            while (!found) {
                if (key < keys[position]) {
                    if (left_child_pos[position] == EMPTY_POSITION) {
                        keys[size] = key;
                        left_child_pos[position] = size;
                        parent_positions[size] = position;
                        ++size;
                        found = true;
                    }
                    else
                    {
                        position = left_child_pos[position];
                    }
                }
                else
                {
                    if (right_child_pos[position] == EMPTY_POSITION) {
                        keys[size] = key;
                        right_child_pos[position] = size;
                        parent_positions[size] = position;
                        ++size;
                        found = true;
                    }
                    else
                    {
                        position = right_child_pos[position];
                    }
                }
            }
        }
    }
 
    // post_order
    size_t position = 0;
    std::vector<size_t> positions;
    std::vector<unsigned int> post_order_keys;
    positions.push_back(position);
 
    while (!positions.empty()) {
        
        position = positions[positions.size() - 1];
        positions.pop_back();
        post_order_keys.push_back(keys[position]);
 
        if (position != EMPTY_POSITION) {
            if (left_child_pos[position] != EMPTY_POSITION) {
                positions.push_back(left_child_pos[position]);
            }
            if (right_child_pos[position] != EMPTY_POSITION) {
                positions.push_back(right_child_pos[position]);
            }
        }
    }
 
    while (!post_order_keys.empty()) {
        std::cout << post_order_keys.at(post_order_keys.size() - 1) << " ";
        post_order_keys.pop_back();
    }
    std::cout << "\n";
 
    // in_order
    position = 0;
    size_t parent_position;
    size_t root_count = 0;
 
    position = find_left_most(position);
    if (position == 0) {
        ++root_count;
        if (root_count == 2) {
            std::cout << "\n";
            return 0;
        }
    }
 
    while (position != EMPTY_POSITION) {
        std::cout << keys[position] << " ";
 
        if (right_child_pos[position] != EMPTY_POSITION) {
            position = find_left_most(right_child_pos[position]);
        }
        else
        {
            parent_position = parent_positions[position];
            if (parent_position != EMPTY_POSITION && 
                right_child_pos[parent_position] == position) {
                
                    position = right_go_up(position);
            }
            else
            {
                position = parent_position;
            }
        }
        if (position == 0) {
            ++root_count;
            if (root_count == 2) {
                std::cout << "\n";
                return 0;
            }
        }
    }
    std::cout << "\n";
 
    return 0;
}
Вот так я попытался выкинуть классы, стало 0,551:-(

Добавлено через 3 минуты
Может не стоит в таких случаях колдунствовать, искать ошибку в алгоритме?
Там наверное в чем то другом ошибка, ибо сейчас показывает Time limit и время 0,472.
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#include <iostream>
#include <vector>
 
 
const unsigned int EMPTY_POSITION = static_cast<unsigned int>(-1);
std::vector<unsigned int> keys;
std::vector<unsigned int> left_child_pos;
std::vector<unsigned int> right_child_pos;
std::vector<unsigned int> parent_positions;
 
inline size_t find_left_most(size_t position) {
    while (position != EMPTY_POSITION && left_child_pos[position] != EMPTY_POSITION) {
        position = left_child_pos[position];
    }
    return position;
}
 
inline size_t right_go_up(size_t position) {
    size_t parent_position = parent_positions[position];
    while (position != EMPTY_POSITION && parent_position != EMPTY_POSITION &&
        right_child_pos[parent_position ] == position) {
 
            position = parent_position;
            parent_position = parent_positions[position];
    }
    if (position == 0) {
        return position;    
    }
    else
    {
        return parent_position;
    }
}
 
int main() {
 
    std::ios_base::sync_with_stdio(false);
 
    unsigned int keys_number;
    std::cin >> keys_number;
 
    keys.resize(keys_number);
    left_child_pos.resize(keys_number, EMPTY_POSITION);
    right_child_pos.resize(keys_number, EMPTY_POSITION);
    parent_positions.resize(keys_number, EMPTY_POSITION);
 
    
    unsigned int key;
    std::cin >> key;
 
    keys[0] = key;
    unsigned int size;
    size = 1;
 
    for (size_t keys_index = 1; keys_index < keys_number; ++keys_index) {
        std::cin >> key;
 
        if (key < keys[size - 1]) {
            keys[size] = key;
            left_child_pos[size - 1] = size;
            parent_positions[size] = size - 1;
            ++size;
        }
        else
        {
            size_t position = size - 1;
            size_t parent_position = parent_positions[position];
            if (parent_position != EMPTY_POSITION && 
                keys[position] <= key && keys[parent_position] <= key) {
 
                    while (parent_position != EMPTY_POSITION && 
                        keys[position] <= key && keys[parent_position] <= key) {
            
                            position = parent_positions[position];
                            parent_position = parent_positions[position];
                    }
 
                    if (right_child_pos[position] != EMPTY_POSITION) {
 
                        while (right_child_pos[position] != EMPTY_POSITION && 
                            position < right_child_pos.size()) {
                        
                                position = right_child_pos[position];
                        }
                    }
                    keys[size] = key;
                    right_child_pos[position] = size;
                    parent_positions[size] = position;
                    ++size;
            }
            else
            {
                keys[size] = key;
                right_child_pos[position] = size;
                parent_positions[size] = position;
                ++size;
            }
        }
    }
 
    // post_order
    size_t position = 0;
    std::vector<size_t> positions;
    std::vector<unsigned int> post_order_keys;
    positions.push_back(position);
 
    while (!positions.empty()) {
        
        position = positions[positions.size() - 1];
        positions.pop_back();
        post_order_keys.push_back(keys[position]);
 
        if (position != EMPTY_POSITION) {
            if (left_child_pos[position] != EMPTY_POSITION) {
                positions.push_back(left_child_pos[position]);
            }
            if (right_child_pos[position] != EMPTY_POSITION) {
                positions.push_back(right_child_pos[position]);
            }
        }
    }
 
    while (!post_order_keys.empty()) {
        std::cout << post_order_keys.at(post_order_keys.size() - 1) << " ";
        post_order_keys.pop_back();
    }
    std::cout << "\n";
 
    // in_order
    position = 0;
    size_t parent_position;
    size_t root_count = 0;
 
    position = find_left_most(position);
    if (position == 0) {
        ++root_count;
        if (root_count == 2) {
            std::cout << "\n";
            return 0;
        }
    }
 
    while (position != EMPTY_POSITION) {
        std::cout << keys[position] << " ";
 
        if (right_child_pos[position] != EMPTY_POSITION) {
            position = find_left_most(right_child_pos[position]);
        }
        else
        {
            parent_position = parent_positions[position];
            if (parent_position != EMPTY_POSITION && 
                right_child_pos[parent_position] == position) {
                
                    position = right_go_up(position);
            }
            else
            {
                position = parent_position;
            }
        }
        if (position == 0) {
            ++root_count;
            if (root_count == 2) {
                std::cout << "\n";
                return 0;
            }
        }
    }
    std::cout << "\n";
 
    return 0;
}
Чуть изменил код без классов: объединив два предыдущих.
0
Мой лучший друг-отладчик!
 Аватар для ZaMaZaN4iK
167 / 167 / 30
Регистрация: 24.06.2012
Сообщений: 662
Записей в блоге: 5
05.12.2013, 21:37
R_e_n, кинь исходник плиз.Может что придумаем.Просто обычно если такие близкие значения к обрубанию, то значит, что алгоритм выбран не совсем удачно. Ну а если знаешь, что алгоритм не подходит, но по другому не можешь решить, то тогда уже оптимизируешь всё.

Я обычно вижу по алгоритму прикидываю, сколько будет работать.Первое - асимптотика. Потом уже смотришь реализацию алгоритмов.

Ну самое банальное, что могу сказать:
1) Замена ввода cin и вывода cout на scanf/printf - они работают значительно быстрее(даже фокус с ios_base::sync_with_stdio(0) не дает такого эффекта).
2) можно чутка сэкономить, делая функции inline
3) все повторяющиеся где-то одинаковые вычисления запоминаются(смотрим, чтобы например каждый раз в цикле корень не извлекался, а просто посчитаем раз и запомним его.Вот такие случаи)
4) передаем допустим в функцию вектор только адрес его, а не прост так - он копирует его в функцию и значительно падает скорость
5) где можно заменяем рекурсию на итеративный метод
6) есть такое правило - чем больше мы используем памяти, тем быстрее работает.Попробуйте может какие-то вычисления сохранять в массив, а потом вместо того, чтобы заново их считать, юзайте из массива.Только не увлекайтесь, а то и ML можно получить
7) подумайте: быть может вспомните какое-то математическое свойство иль формулу, которое реально поможет в задаче.

Можно много чего ещё, но это первое, что прищло
1
0 / 0 / 0
Регистрация: 30.07.2012
Сообщений: 38
05.12.2013, 21:41  [ТС]
Спасибо, буду ошибку искать
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
05.12.2013, 21:41
Помогаю со студенческими работами здесь

Как посчитать время выполнения программы?
Как посчитать время выполнения программы? нужно узнать за сколько секунд сортируются данные покажите на примере спасибо...

Как получить время выполнения программы?
подскажите, пожалуйста, как засечь время выполнения программы. нигде найти не могу=( пишут, что это переменная типа TTime и всё... ...

Как определить время выполнения программы?
как определить время выполнения программы

Как ускорить время выполнения программы
Добрый день :) Исходные данные В единственной строке находится целое число N, 1 ≤ N ≤ 10^9. Результат Следует...

Как ограничить время выполнения программы?
Добрый день! Задали написать программу, следующего содержания: &quot;Для натурального числа сумма знакопеременного натурального ряда до...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru