完整代码:
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <map> #include <cmath> using namespace std; int main() { int t; scanf("%d",&t); while(t--) { long x=0,y=0; int n,k; char c,ch[100010]; long mmax=0; scanf("%d%d",&n,&k); getchar(); for(int i=0;i<n;i++) { scanf("%c",&c); ch[i]=c; if(c=='U') { y++; } else if(c=='D') { y--; } else if(c=='L') { x--; } else{ x++; } if(abs(x)+abs(y)>mmax) { mmax=abs(x)+abs(y); } } x*=k; y*=k; for(int i=n-1;i>=0;i--) { if(abs(x)+abs(y)>mmax) { mmax=abs(x)+abs(y); } if(ch[i]=='U') { y--; } else if(ch[i]=='D') { y++; } else if(ch[i]=='L') { x++; } else{ x--; } if(abs(x)+abs(y)>mmax) { mmax=abs(x)+abs(y); } } printf("%ld\n",mmax);//最后结果一定只能出现在第一轮或最后一轮,所以只要找这两轮中的最大值就行了