最优屏障
插入屏障后,区间被分为[1,x]和[x+1,n]两个部分。可以利用栈来求出前缀的对数和、后缀的对数和,前缀和表示连续下降的山的个数,后缀和同理。然后在一个for循环来寻找最大值,减少的最大防守力就是[1,n] - [1,x] - [x+1,n],最优的屏障放置位置就是当前的x+1。
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
#define N 200000
int t,n,ans,pos,sum,vis1[N],vis2[N],a[N];
stack<int>st;
int main(void){
scanf("%d",&t);
for(int k = 1;k <=t;k++){
cin>>n;
vis1[0] = vis2[n+1] = ans = pos = 0;
for(int i = 1;i <=n;i++)
scanf("%d",&a[i]);
while(st.size())
st.pop();
for(int i = 1;i <=n;i++){
vis1[i] = vis1[i-1];
sum = 0;
while(!st.empty()&&st.top()<a[i]){
sum++;
st.pop();
}
if(!st.empty())
vis1[i] +=sum+1;
else
vis1[i] +=sum;
st.push(a[i]);
}
while(!st.empty())
st.pop();
for(int i = n;i>=1;i--){
vis2[i] = vis2[i+1];
sum = 0;
while(!st.empty()&&st.top()<a[i]){
sum++;
st.pop();
}
if(!st.empty())
vis2[i] +=sum+1;
else
vis2[i] +=sum;
st.push(a[i]);
}
for(int i = 1;i<=n;i++){
if(vis1[n]-vis1[i]-vis2[i+1]>ans){
ans = vis1[n] - vis1[i] -vis2[i+1];
pos = i + 1;
}
}
printf("Case #%d: %d %d\n",k,pos,ans);
}
return 0;
}
吐泡泡
用stack模拟即可
#include<bits/stdc++.h>
using namespace std;
int main()
{
string a;
while(cin>>a)
{
if(a.length()==1) cout<<a<<endl;
else
{
stack<char>s;
s.push(a[0]);
for(int i=1;i<a.length();i++)
{
if(s.empty())
s.push(a[i]);
else
{
if(s.top()==a[i])
{
if(s.top()=='O')
s.pop();
else
{
s.pop();
if(!s.empty())
{
if(s.top()=='o')
s.push('O');
else
s.pop();
}
else s.push('O');
}
}
else
s.push(a[i]);
}
}
stack<char>s1;
while(!s.empty())
{
s1.push(s.top());
s.pop();
}
while(!s1.empty())
{
cout<<s1.top();
s1.pop();
}
cout<<endl;
}
}
}
Rails
注意输出
#include <bits/stdc++.h>
using namespace std;
int s[1005];
int n = 0;
bool check()
{
int j = 0;
stack<int> a;
for (int i = 1; i <= n; i++)
{
a.push(i);
while (!a.empty() && a.top() == s[j])
{
a.pop();
j++;
}
}
if (a.empty())
{
return true;
}
else
return false;
}
int main()
{
int flags = 0;
int buf = 0;
while (1)
{
cin >> buf;
if (!buf)
break;
else
{
n = buf;
if (flags)
cout << endl;
}
while (1)
{
cin >> buf;
if (buf)
{
s[0] = buf;
for (int i = 1; i < n; i++)
cin >> s[i];
flags = 1;
if (check())
cout << "Yes" << endl;
else
cout << "No" << endl;
}
else
break;
}
}
return 0;
}