| 개선점 | 이유 |
|---|
while (!target.empty()) | 더 직관적이고 안전 |
matched 지역 변수 사용 | 범위 최소화, 코드 명확성 향상 |
for (auto &p : parrots) | 복사 방지, 성능 향상 |
any_of 사용 | 남은 단어 판별을 간결하게 표현 |
| 코드 라인 수 ↓ | 가독성, 유지보수성 향상 |
성능 비교
- My code :
4492KB, 12ms
- Optimized code :
4624KB, 8ms
#include <iostream>
#include <sstream>
#include <deque>
#include <vector>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
cin.ignore();
vector<deque<string>> sentences;
while(n--) {
deque<string> temp;
string line;
getline(cin, line);
stringstream ss(line);
string word;
while (ss >> word) {
temp.push_back(word);
}
sentences.push_back(temp);
}
deque<string> target;
string line;
getline(cin, line);
stringstream ss(line);
string word;
while (ss >> word) {
target.push_back(word);
}
bool isPossible;
while (target.size() > 0) {
isPossible = false;
for (auto& sentence : sentences) {
if (!sentence.empty() && sentence.front() == target.front()) {
sentence.pop_front();
target.pop_front();
isPossible = true;
break;
}
}
if (!isPossible) break;
}
if (!isPossible || target.size() > 0) {
cout << "Impossible";
} else {
for (deque<string> sentence : sentences) {
if (sentence.size() > 0) {
cout << "Impossible";
return 0;
}
}
cout << "Possible";
}
return 0;
}
- Code optimized by ChatGPT
#include <iostream>
#include <sstream>
#include <deque>
#include <vector>
#include <string>
#include <algorithm> // for any_of
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
cin.ignore();
vector<deque<string>> parrots(n);
for (int i = 0; i < n; ++i) {
string line, word;
getline(cin, line);
stringstream ss(line);
while (ss >> word) parrots[i].push_back(word);
}
string line, word;
getline(cin, line);
stringstream ss(line);
deque<string> target;
while (ss >> word) target.push_back(word);
// 메인 로직
while (!target.empty()) {
bool matched = false;
for (auto &p : parrots) {
if (!p.empty() && p.front() == target.front()) {
p.pop_front();
target.pop_front();
matched = true;
break;
}
}
if (!matched) {
cout << "Impossible";
return 0;
}
}
// 아직 말 안 끝낸 앵무새가 있다면 Impossible
bool remain = any_of(parrots.begin(), parrots.end(),
[](const deque<string>& p) { return !p.empty(); });
cout << (remain ? "Impossible" : "Possible");
return 0;
}