一、栈的应用
c++的栈
#include<bits/stdc++.h>
using namespace std;
stack<int> S;
int main(){
S.push(1);
S.push(10);
S.push(7);
while(!S.empty()){
cout << S.top() << endl;
S.pop();
}
return 0;
}
c语言的栈
//栈和队列都可以用数组模拟实现
#include <stdio.h>
int st[1005];//定义一个栈
int main() {
int top = 0;//栈顶下标
st[++top] = 1;//将1入栈
st[++top] = 10;//将10入栈
st[++top] = 7;//将7入栈
while (top > 0) {//当栈不为空
printf("%d\n", st[top]);//输出栈顶元素
top--;//将栈顶元素出栈
}
return 0;
}
1 括号匹配
每个元素和栈顶元素匹配,匹配上了出栈,否则入栈。最后判断栈是否为空。
#include<bits/stdc++.h>
using namespace std;
int main(){
char s[300];
scanf("%s", &s);
int len = strlen(s);
stack<char> st;
for(int i = 0; i < len; ++i){
if(!st.empty()){
char now = st.top();
if((s[i] == ')'&&now == '(')||(s[i] == ']'&&now == '[')){
st.pop();
}
else st.push(s[i]);
}
else{
st.push(s[i]);
}
}
if(!st.empty()) printf("NO\n");
else printf("YES\n");
return 0;
}
带优先级的括号匹配,增加一个判断即可
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
scanf("%d", &n);
for(int i = 0; i < n; ++i){
char s[300];
scanf("%s", &s);
int len = strlen(s);
stack<char> st;
for(int i = 0; i < len; ++i){
if(!st.empty()){
char now = st.top();
if(now == '<'&&(s[i] == '('||s[i] == '['||s[i] == '{')||now == '('&&(s[i] == '['||s[i] == '{')||now == '['&&s[i] == '{'){
break;
}
else if((s[i] == ')'&&now == '(')||(s[i] == ']'&&now == '[')||(s[i] == '}'&&now == '{')||(s[i] == '>'&&now == '<')){
st.pop();
}
else st.push(s[i]);
}
else st.push(s[i]);
}
if(!st.empty()) printf("NO\n");
else printf("YES\n");
}
return 0;
}
二、优先队列
带顺序的队列 priority queue<int, vector, greater> q;
合并果子,每次合并后,加入优先队列,这样会重排序。
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
priority_queue<int, vector<int>, greater<int>> q;
int x;
int energy;
int sum=0;
for(int i = 0; i < n; i++){
cin >> x;
q.push(x);
}
while(q.size()!=1){
int w = q.top();
q.pop();
int v = q.top();
q.pop();
energy = w + v;
q.push(energy);
sum += energy;
}
cout << sum << endl;
return 0;
}