Simple Robot Gym - 101102I (思维)

SaMer is building a simple robot that can move in the four directions: up (^), down (v), left (<), and right (>). The robot receives the commands to move as a string and executes them sequentially. The robot skips the commands that make it go outside the table.

SaMer has an R×C table and a string of instructions. He wants to place the robot on some cell of the table without rotating it, such that the robot will skip the minimum number of instructions. Can you help him find the number of instructions that will be skipped by the robot if it was placed optimally?

Input

The first line of input contains a single integer T, the number of test cases.

Each test case contains two space-separated integers R and C (1 ≤ R, C ≤ 105), the number of rows and the number of columns in the table, followed by a non-empty string of no more than 200000 characters representing the initial instructions. The instructions are executed in the given order from left to right.

Output

For each test case, print the minimum number of instructions which will be skipped, on a single line.

Example

Input
2
2 2 >^<v>^^<v
3 4 >^<^vv<>v>>v
Output
1
2

题意:
给一个n*m的格子,以及一串移动序列,如果移动超出边界,则会跳过这个操作,问最少会跳过多少个序列(起点未定)
思路:
没必要确定起点,如果在同一方向上走出的距离长度超出了棋盘长度的,那就是要跳过的操作。
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#define fuck(x) cout<<#x<<" = "<<x<<endl;
#define debug(a,i) cout<<#a<<"["<<i<<"] = "<<a[i]<<endl;
#define ls (t<<1)
#define rs ((t<<1)+1)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 200086;
const int maxm = 100086;
const int inf = 2.1e9;
const ll Inf = 999999999999999999;
const int mod = 1000000007;
const double eps = 1e-6;
const double pi = acos(-1);

char s[maxn];

int main()
{
//    ios::sync_with_stdio(false);
//    freopen("in.txt","r",stdin);

    int T;
    scanf("%d",&T);
    while(T--){
            int n,m;
        scanf("%d%d",&n,&m);
        scanf("%s",s);
        int len=strlen(s);
        int x,y;
        x=y=0;
        int x1,x2,y1,y2;
        x1=x2=y1=y2=0;
        int ans=0;
        for(int i=0;i<len;i++){
            if(s[i]=='^'){y++;if(y-y1>=n){ans++;y--;continue;}}
            else if(s[i]=='v'){y--;if(y2-y>=n){ans++;y++;continue;}}
            else if(s[i]=='>'){x++;if(x-x1>=m){ans++;x--;continue;}}
            else{
                x--;if(x2-x>=m){ans++;x++;continue;}
            }
//            cout<<i<<" "<<x<<" "<<x1<<endl;
            x1=min(x1,x);
            x2=max(x2,x);
            y1=min(y1,y);
            y2=max(y2,y);
        }
        printf("%d\n",ans);
    }

    return 0;
}
/*
5
1 5
>>>>><<<<<
*/
View Code
 
 

猜你喜欢

转载自www.cnblogs.com/ZGQblogs/p/10840880.html