Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- typedef long long int ll;
- #define FAST_IO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
- #define pb push_back
- int main(){
- FAST_IO
- ll t;
- cin>>t;
- while(t--){
- ll m,n;
- cin>>m>>n;
- vector<pair<ll,ll> > position;
- char ch;
- bool start = true;
- ll curr_i = -1,curr_j = -1;
- ll last_i = -1;
- for(ll i=1;i<=m;i++){
- bool first = true;
- ll left_j=-1, right_j=-1;
- for(ll j=1;j<=n;j++){
- cin>>ch;
- if(ch=='P'){
- if(first)left_j=j;
- right_j = j;
- first=false;
- last_i = i;
- }
- }
- position.pb({left_j,right_j});
- if(start and left_j!=-1){
- start = false;
- curr_i = i;
- if(i%2==0){
- curr_j=right_j;
- }
- else{
- curr_j=left_j;
- }
- }
- }
- ll steps = 0;
- if(curr_i==-1 and curr_j==-1){
- cout<<steps<<endl;
- }
- else{
- for(ll i=curr_i;i<=last_i;i++){
- // cout<<i<<" "<<curr_j<<" "<<steps<<endl;
- if(i%2!=0){
- if(position[i-1].first!=-1){
- steps += position[i-1].second - curr_j;
- curr_j = position[i-1].second;
- }
- if(i<=m-1){
- if(position[i].first!=-1){
- if(position[i].second>curr_j){
- steps += position[i].second - curr_j;
- curr_j = position[i].second;
- }
- }
- }
- steps+=1; ///going to next level
- }
- else{
- if(position[i-1].first!=-1){
- steps += curr_j - position[i-1].first;
- curr_j = position[i-1].first;
- }
- if(i<=m-1){
- if(position[i].first!=-1){
- if(position[i].first<curr_j){
- steps+=curr_j - position[i].first;
- curr_j = position[i].first;
- }
- }
- }
- steps+=1; ///going to next level
- }
- }
- steps-=1;
- cout<<steps<<endl;
- }
- }
- }
Add Comment
Please, Sign In to add comment