ACM 入门 Have Fun with String I

Given a string consists only of the digits “1” and “3”. We all know that number 13 is so called unlucky number. Therefore, we decided to remove some digits from the string so that the damned number 13 would not occur in it. Of course, we want to do it as quickly as possible, and now he is wondering what minimal number of symbols can be deleted.
Input
There are multiple test cases. The first line of input is an integer T indicate the number of test cases. For each test case:
The only line of the input contains a string. This string is not empty, its length does not exceed 1000 symbols, and its symbols are only digits “1” and “3”.
Output
Print one integer - the answer for each case.
Sample Input
3
313
1133
113133
Sample Output
1
2
3

#include <bits/stdc++.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    for(int i=1;i<=t;i++){
        int min=10000;
        char emm[1005];
        cin>>emm;
        int k=strlen(emm);
        int sum1[1005]={0};
        int sum3[1005]={0};//维护两个数组,下标为i保存之前的序列中(不包括i)1的个数,3的个数
        int num_1=0;
        int num_3=0;
        for(int q=0;q<=k;q++){
            sum1[q]=num_1;
            sum3[q]=num_3;
            if(emm[q]=='1'){
                num_1++;
            }
            else if(emm[q]=='3'){
                num_3++;
            }
        }
        min=k-1;
        for(int i=0;i<=k-1;i++){
            int temp;
            temp=sum1[i]+sum3[k]-sum3[i+1];  //删掉i之前所有的1,删掉i之后所有的3
            if(temp<min){
                min=temp;
            }
        }
        printf("%d\n",min );
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38677814/article/details/80113205