CF1202C You Are Given a WASD-string... 题解
CF1202C You Are Given a WASD-string... 题解
题目传送
题意
有一个机器人,给出一个只由
分析与思路
我们可以把字符串中的上下走和左右走的分开,分别统计最上面,最下面,最左面,最右面到达的位置(假设初始位置为
实现
统计上下左右方向的最值很简单,接着最难得部分就是判断能不能缩小。我们定义
先处理横着的,想要变小最大值,就必须在它第一次出现之前插入一个能使最大值变小的字母,而且不能在最小值最后一次出现之前插入,因为这样会使最大值与最小值同时变大或变小,极差还是没有变(例如
竖着的同理,最后在给这两种情况(减小横着的极差,减小竖着的极差)取最小值即可(不减小的答案为(最右面-最左面+
Code
#include <bits/stdc++.h>
//#include <windows.h>
//#include <psapi.h>
//#include <time.h>
using namespace std;
#define debug(x) std::cerr<<#x<<'='<<x<<std::endl
#define int long long
int sideway,vertical;//分别为横,竖
int up,down,lft,rigt;
int upfirstime,downfirstime,leftfirstime,rightfirstime;
int uplastime,downlastime,leftlastime,rightlastime;
string reset(string a){//将字符串改为从 1 开始
string t="+";
for(int i=0;i<a.size();i++)t+=a[i];
a="";
a+=t;
return a;
}
void clear(){//清空
sideway=vertical=0;
up=down=lft=rigt=0;
upfirstime=downfirstime=leftfirstime=rightfirstime=0;
uplastime=downlastime=leftlastime=rightlastime=0;
}
void handle(string a){//记录每个最值的两个时间
for(int j=1;j<=a.size();j++){
if(a[j]=='W')vertical++;
else if(a[j]=='S')vertical--;
else if(a[j]=='A')sideway--;
else if(a[j]=='D')sideway++;
if(vertical>up)up=vertical,upfirstime=j;
if(vertical==up)uplastime=j;
if(vertical<down)down=vertical,downfirstime=j;
if(vertical==down)downlastime=j;
if(sideway>rigt)rigt=sideway,rightfirstime=j;
if(sideway==rigt)rightlastime=j;
if(sideway<lft)lft=sideway,leftfirstime=j;
if(sideway==lft)leftlastime=j;
}
// debug(vertical);
// debug(sideway);
}
signed main()
{
// freopen("Luogu_CF_1202_C.cpp.in","r",stdin);
// freopen("Luogu_CF_1202_C.cpp.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin>>n;
string a;
for(int i=1;i<=n;i++){
cin>>a;
int ans=0;
a=reset(a);
// cout<<a<<" ";
clear();
handle(a);
ans=(up-down+1)*(rigt-lft+1);//不减小的面积
if(leftfirstime-rightlastime>1 or rightfirstime-leftlastime>1)ans=min(ans,(up-down+1)*(rigt-lft));
if(upfirstime-downlastime>1 or downfirstime-uplastime>1)ans=min(ans,(up-down)*(rigt-lft+1));
cout<<ans<<"\n";//判断,取最小值
}
// fclose(stdin);
// fclose(stdout);
return 0;
}
本蒟蒻水平有限,如有不周之处,希望能原谅。