PAT--1092 To Buy or Not to Buy (20 分)

Eva would like to make a string of beads with her favorite colors so she went to a small shop to buy some beads. There were many colorful strings of beads. However the owner of the shop would only sell the strings in whole pieces. Hence Eva must check whether a string in the shop contains all the beads she needs. She now comes to you for help: if the answer is Yes, please tell her the number of extra beads she has to buy; or if the answer is No, please tell her the number of beads missing from the string.

For the sake of simplicity, let's use the characters in the ranges [0-9], [a-z], and [A-Z] to represent the colors. For example, the 3rd string in Figure 1 is the one that Eva would like to make. Then the 1st string is okay since it contains all the necessary beads with 8 extra ones; yet the 2nd one is not since there is no black bead and one less red bead.

figbuy.jpg

Figure 1

Input Specification:

Each input file contains one test case. Each case gives in two lines the strings of no more than 1000 beads which belong to the shop owner and Eva, respectively.

Output Specification:

For each test case, print your answer in one line. If the answer is Yes, then also output the number of extra beads Eva has to buy; or if the answer is No, then also output the number of beads missing from the string. There must be exactly 1 space between the answer and the number.

Sample Input 1:

ppRYYGrrYBR2258
YrR8RrY

Sample Output 1:

Yes 8

Sample Input 2:

ppRYYGrrYB225
YrR8RrY

Sample Output 2:

No 2
#include <iostream>
#include <bits/stdc++.h>

using namespace std;


int main()
{
    string str,str1;
    cin>>str;
    cin>>str1;
    int tmp =0;
    int shop_count[150]= {0};
    int mine_count[150]= {0};
    int len1 = str.length();
    int len2 = str1.length();
    for(int i=0; i<len1; i++)
    {
        //cout<<str[i];
        shop_count[str[i]]++;
        //check_char(shop_count,str[i]);
    }

    for(int i=0; i<len2; i++)
    {
        mine_count[str1[i]]++;
        //check_char(mine_count,str1[i]);
    }
    int flag = 0;
    int counts = 0;
    int counts1 = 0;
    for(int i=0; i<150; i++)  //必须小于150,不可等于!!!
    {
        // cout<<i<<" "<<num[i]<<" "<<num1[i]<<endl;
        if(shop_count[i]<mine_count[i])
        {
            //cout<<i;
            flag =1;
            counts +=mine_count[i]-shop_count[i];
        }
        else
        {
           continue;
        }
    }

    if(flag ==0 )
    {
        cout<<"Yes"<<" "<<len1-len2<<endl; //若足够,则之间用长度减就可以
    }
    else
    {
        cout<<"No"<<" "<<counts<<endl;
    }
    //cout<<str<<endl<<str1<<endl<<len1<<" "<<len2;
    return 0;
}

 分析:

刚开始的思路是:用一个int型数组存储字符串中出现的字符的个数,可是因为长时间不敲代码,不知道怎么对应,查资料无果后,我就“暴力”对应,定义一个150的数组,将每个字符num[str[i]]直接对应,可以通过,但是前几次提交在判断最后的循环的时候,因为数组意识不够,写了<=150导致错了好几次,还以为是对应问题,最后在参考了其他人的代码并进行调试后才发现问题。

猜你喜欢

转载自blog.csdn.net/jackson_j/article/details/98501807