ACM刷題之codeforces————Simple Robot

Simple Robot
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<string>
#include<iostream>
using namespace std;
#define MID(x,y) ((x+y)>>1)
#define CLR(arr,val) memset(arr,val,sizeof(arr))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int N=2e5+7;

char d[200005];

int main()
{
	//freopen("f:/input.txt", "r", stdin);
	int zu,i,j,k,n,m,len1,x,y,sum,minx,miny,maxx,maxy;
	scanf("%d",&zu);
	while(zu--)
	{
		scanf("%d %d %s",&n,&m,&d);
		len1 = strlen(d);
		x=y=1;
		sum=0;
		miny=minx=maxy=maxx=1;
		for(i=0;i<len1;i++)
		{
			if(d[i]=='>')
			{
				if(x+1-minx<m)
				{
					++x;
					if(x>maxx)
					{
						maxx=x;
					}
					continue;
				}else {
					++sum;
				}
			}
			
			if(d[i]=='<')
			{
				if(maxx-(x-1)<m)
				{
					--x;
					if(x<minx)
					{
						minx=x;
					}
					continue;
				}else{
					++sum;
				}
			}
			
			if(d[i]=='^')
			{
				if(y+1-miny<n)
				{
					++y;
					if(y>maxy)
					{
						maxy=y;
					}
					//maxy= maxy+1;
					continue;
				}else{
					++sum;
				}
			}
			
			if(d[i]=='v')
			{
				if(maxy-(y-1)<n)
				{
					--y;
					if(y<miny)
					{
						miny=y;
					}
					//miny=miny-1;
					continue;
				}else{
					++sum;
				}
			}
		}
		
		printf("%d\n",sum);
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章