백준 10773번 - Silver IV
#include <iostream>
#include <stack>
using namespace std;
stack <int> stk; // stack 생성
int main(void){
ios::sync_with_stdio(false);
cin.tie(NULL);
int i,k,num;
int sum=0;
cin>>k;
for(int i=0;i<k;i++){
cin>>num;
if(num==0)
stk.pop();
else
stk.push(num);
}
for(i=0;!stk.empty();i++){
sum += stk.top();
stk.pop();
}
cout<< sum <<"\n";
return 0;
}
백준 10773번 - Silver IV
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool comparefunc(string str){
int len = (int)str.length();
stack <char> s;
for(int i=0;i<len;i++){
char chk = str[i];
if(chk=='('){
s.push(str[i]);
}else{
if(!s.empty())
s.pop();
else
return false;
}
}
return s.empty();
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >>t;
for(int i=0;i<t;i++){
string str;
cin>>str;
if(comparefunc(str))
cout <<"YES"<<"\n";
else
cout << "NO"<<"\n";
}
return 0;
}
백준 4949번 - Silver IV
1) 함수 사용
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool comparefunc(string str){
int len = (int)str.length();
stack <char> s;
int cnt=0, flag=0;
for(int i=0;i<len;i++){
char chk = str[i];
if(chk=='('||chk=='['){
s.push(chk);
}else if(chk==')'){
if(s.empty()|| s.top()!='('){
flag=1;
break;
}
s.pop();
}else if(chk==']'){
if(s.empty()|| s.top()!='['){
flag=1;
break;
}
s.pop();
}
}
if(flag||!s.empty())
return false;
else
return true;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
while(1){
string str;
getline(cin,str);
if(str==".")
break;
if(comparefunc(str)==true)
cout <<"yes\n";
else
cout << "no\n";
}
return 0;
}
2) 함수 X
#include <iostream>
#include <stack>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
while(1){
stack <char> s;
string str;
getline(cin,str);
if(str=="."){
break;
}
int flag=0;
for(int i=0;i<str.size();i++){
char chk = str[i];
if(chk=='(' || chk=='['){
s.push(chk);
}else if(chk == ')'){
if(s.empty() || s.top()!='('){
flag=1;
break;
}
s.pop();
}
else if(chk == ']'){
if(s.empty()|| s.top()!='['){
flag=1;
break;
}
s.pop();
}
}
if(flag||!s.empty())
cout << "no\n";
else
cout <<"yes\n";
}
return 0;
}
'코딩 > C++' 카테고리의 다른 글
백준 - 큐, 우선순위 큐 (0) | 2022.04.27 |
---|---|
C++ 알고리즘 - 백준 Stack , Queue (0) | 2022.04.06 |
C++ 알고리즘 - 이진검색의 시간복잡도 (0) | 2022.03.29 |
C++ 알고리즘 - binary search, complexity (0) | 2022.03.26 |
C++ 알고리즘 - 검색 (0) | 2022.03.24 |