这个题一开始是模拟法。从头到尾遍历,根据左右两边的高度来选择
1.如果这个位置左右两边的块都比自身高1块,则不行
2.如果这个位置是最后一个位置,则这个位置的高度可以加到比左边高1或者和左边一样
3.如果不是最后一个位置,则这个位置可以左边的一起加到和右边一样高,或者自己单独比右边高1或者一样高
这样做铁超市,test6和test8都是TLE。当时很无助
后来看网上的更加优化的解法,是栈模拟。如果差距为偶数,则消去,如果差距为奇数,则入栈。
超时代码
#include<cstdio>
using namespace std;
const int maxh=1e9+5;
int n,mx=0,ct=1,h[200000],cont=0;
bool fillh(){
int pos=1;
while(ct!=n){
int left=h[pos-1]-h[pos];
int right=h[pos+1]-h[pos];
if(left==1&&right==1){
return false;
}
//printf("pos=%d height=%d\n",pos,h[pos]);
if(pos==n){
while(left>0){
// if(cont>200000000) return true;
// else cont++;
//printf("pos=%d height=%d\n",pos,h[pos]);
h[pos]=(left%2?h[pos-1]+1:h[pos-1]);
left=h[pos-1]-h[pos];
}
pos=1;
}
else while(right>0){
// if(cont>200000000) return true;
// else cont++;
//
//printf("222pos=%d height=%d\n",pos,h[pos]);
if(left==0){
h[pos-1]+=right;
h[pos]+=right;
// printf("233333333332pos=%d height=%d\n",pos,h[pos]);
}
else{
// printf("left= %d right=%d\n",left,right);
if(left<right&&left>0)
{
if(!(left%2))
{
h[pos]=h[pos-1];
}
}
else{
h[pos]=(right%2?h[pos+1]+1:h[pos+1]);
// printf("23333322pos=%d height=%d\n",pos,h[pos]);
}
}
right=h[pos+1]-h[pos];
}
if(mx<h[pos]){
mx=h[pos];
ct=1;
}
else if(mx==h[pos]){
ct++;
}
pos++;
// if(cont>200000000) return true;
// else cont++;
}
return true;
}
bool fillh2(){
int pos=1;
// printf("%d",mx);
for(int i=1;i<=n;i++){
if(h[i]<mx-1){
int cha=mx-h[i];
h[i]=(cha%2?mx-1:mx);
}
}
for(int i=1;i<=n;i++){
printf("h[%d]=%d\n",i,h[i]);
if((h[i-1]-h[i]==1)&&(h[i+1]-h[i]==1)){
return false;
}
}
return true;
}
int main(void){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&h[i]);
if(h[i]>mx) mx=h[i];
}
h[0]=maxh;
h[n+1]=maxh;
if(fillh()){
printf("YES");
}
else{
printf("NO");
}
}
优化代码
#include<cstdio>
#include<cstring>
#include<stack>
#include<iostream>
#include<algorithm>
using namespace std;
int main(void){
stack<int> s;
while(!s.empty()) s.pop();
int n;
cin>>n;
for(int i=0;i<n;i++){
int h;
scanf("%d",&h);
if(s.empty()){
s.push(h);
}
else{
if((abs(s.top()-h))%2){
s.push(h);
}
else{
s.pop();
}
}
}
// while(!s.empty()){
// printf("%d",s.top());
// s.pop();
// }
if(s.size()<2){
printf("YES");
}
else
printf("NO");
}