CF1272B-Snow Walking Robot

题目:https://vjudge.net/problem/CodeForces-1272B#author=W873243475

题意:给出字符串,在每个字符串中任意选择从而组成长度最大的、能使robot回到原点且途中经过的点不重复的字符串。U,D,L,R分别表示上下左右。

分析:容易得到要回到原点,上和下、左和右移动的距离必须相等,故每读取一个字符串,统计四个字母出现的次数,并且取上和下中的最小值以及左和右中的最小值,最后根据这两个值组成所求的字符串。具体见代码。

 1 #include <stdio.h>
 2 #include <string.h>
 3 int main(void){
 4     int t;
 5     scanf("%d",&t);
 6     while(t--){
 7         char s[201000]={'\0'};
 8         int a[4]={0};
 9         scanf("%s",s);
10         int l=strlen(s);
11         for(int i=0;i<l;i++){
12             switch(s[i]){//统计次数 
13                 case 'U':a[0]++;break;
14                 case 'D':a[1]++;break;
15                 case 'L':a[2]++;break;
16                 case 'R':a[3]++;break;
17             }
18         }
19         int q=a[0]>a[1]?a[1]:a[0];
20         int p=a[2]>a[3]?a[3]:a[2];
21         if(q==0&&p==0){//两个最小值都为0,无法回到原点 
22             printf("0\n\n");
23         }
24         if(q==0&&p!=0){//有一个为0,只能走两步 
25             printf("2\nLR\n");
26         }
27         if(q!=0&&p==0){
28             printf("2\nUD\n");
29         }
30         if(q!=0&&p!=0){//都不为0,构造字符串 
31             char c[201000]={'\0'};
32             int h=0;
33             for(int i=1;i<=q;i++){
34                 c[h]='U';
35                 h++;
36             }
37             for(int i=1;i<=p;i++){
38                 c[h]='L';
39                 h++;
40             }
41             for(int i=1;i<=q;i++){
42                 c[h]='D';
43                 h++;
44             }
45             for(int i=1;i<=p;i++){
46                 c[h]='R';
47                 h++;
48             }
49             printf("%d\n%s\n",2*(q+p),c);
50         }
51     }
52     return 0;
53 } 

猜你喜欢

转载自www.cnblogs.com/yanying7/p/12323422.html