首页 > 试题广场 >

To Buy or Not to Buy (20)

[编程题]To Buy or Not to Buy (20)
  • 热度指数:2337 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
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 string "YrR8RrY" is the one that Eva would like to make. Then the string "ppRYYGrrYBR2258" is okay since it contains
all the necessary beads with 8 extra ones; yet the string "ppRYYGrrYB225" is not since there is no black bead and one less red bead.

输入描述:
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.


输出描述:
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.
示例1

输入

ppRYYGrrYBR2258<br/>YrR8RrY

输出

Yes 8
#include <iostream>
#include <cstring>
using namespace std;

int main(){
    int hash[128]={0};
    char a[1010],b[1010];
    cin>>a>>b;
    int len1=strlen(a);
    int len2=strlen(b);
    for(int i=0;i<len1;i++)
        hash[a[i]]++;
    int num=0;
    for(int i=0;i<len2;i++){
        if(hash[b[i]]>0){
            hash[b[i]]--;
            num++;
        }
    }
    if(num==len2) cout<<"Yes"<<" "<<len1-num<<'\n';
    else cout<<"No"<<" "<<len2-num<<'\n';

    return 0;
}

发表于 2018-01-25 11:09:09 回复(1)
完全不理解这道题为什么大家代码那么繁杂,明明我用c语言几行代码的事

#include<stdio.h>

int main()
{
	int amount[128]={0},l1,l2,lack=0,d;
	for(l1=0;(d=getchar())!=10;l1++)amount[d]++;
	for(l2=0;(d=getchar())!=10;l2++)if((amount[d]--)<1)lack++;
	if(lack)printf("No %d",lack);
	else printf("Yes %d",l1-l2);
}


发表于 2019-11-26 10:26:24 回复(1)
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        String buyStr=sc.next();
        String need=sc.next();
        HashMap<String,Integer> hashMap=new HashMap<String,Integer>();
        for(int i=0;i<buyStr.length();i++){
            if(hashMap.get(buyStr.charAt(i)+"")==null){
                hashMap.put(buyStr.charAt(i)+"",1);
            }else{
                hashMap.put(buyStr.charAt(i)+"",hashMap.get(buyStr.charAt(i)+"")+1);
            }
        }
        int miss=0;
        for(int i=0;i<need.length();i++){
            if(hashMap.get(need.charAt(i)+"")==null || hashMap.get(need.charAt(i)+"")==0){
                miss++;
            }else{
                hashMap.put(need.charAt(i)+"",hashMap.get(need.charAt(i)+"")-1);
            }
        }
        if(miss==0){
            System.out.println("Yes "+(buyStr.length()-need.length()));
        }else{
            System.out.println("No "+miss);
        }
    }
}

发表于 2018-10-06 11:01:30 回复(0)
其实就是买珠子问题  有自己需要的就买并看看自己需要多买多少个已经有了的  如果没有自己需要的
就不买 并算出一共差多少个珠子

利用Map 先把所有的珠子都放里面 统计每种不同珠子的个数
然后遍历 需要的珠子
--count
做出判断即可。。。

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String allBoss = scanner.next();
        char[] allBosss = allBoss.toCharArray();
        String hasColor = scanner.next();
        char[] hasColors = hasColor.toCharArray();
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for (int i = 0; i < allBosss.length; i++) {
            if (map.containsKey(allBosss[i])) {
                int count = map.get(allBosss[i]);
                map.put(allBosss[i], ++count);
            }else {
                map.put(allBosss[i], 1);
            }
        }
        String str = "";
        for (int i = 0; i < hasColors.length; i++) {
            if (!map.containsKey(hasColors[i])) {
                str += hasColors[i];
            }else {
                int count = map.get(hasColors[i]);
                map.put(hasColors[i], --count);
                if (count<0) {
                    str += hasColors[i];
                }
            }
        }
        if (str.length()>0) {
            System.out.println("No "+str.length());
        }else{
            System.out.println("Yes "+(allBosss.length-hasColors.length));
        }
    }

}

发表于 2018-09-05 09:17:49 回复(0)
public class Main {
    public static void main(String[] args) {
        java.util.Scanner input = new java.util.Scanner(System.in);
        String s1 = input.nextLine();
        String s2 = input.nextLine();
        
        // 使用长度为 62 数组记录每个颜色的数量,
        // 下标范围 0 - 9 表示 [0-9],
        // 下标范围 10 -35 表示 [a-z],
        // 下标范围 36 - 61 表示 [A-Z]
        int[] colors = new int[62];
        for (int i = 0; i < s1.length(); i++) {
            colors[char2index(s1.charAt(i))]++;
        }
        
        // 扫描需要使用到的颜色,每扫描一个颜色,就将 colors 中对应的颜色的数量减去 1
        for (int i = 0; i < s2.length(); i++) {
            colors[char2index(s2.charAt(i))]--;
        }
        
        int extraNum = 0; // 记录多余的颜色数量
        int missingNum = 0; // 记录缺失的颜色数量
        for (int num : colors) {
            if (num > 0) {
                extraNum += num;
            } else if (num < 0) {
                missingNum -= num;
            }
        }
        
        // 输出结果
        if (missingNum > 0) {
            System.out.print("No " + missingNum);
        } else {
            System.out.print("Yes " + extraNum);
        }
        
        input.close();
    }
    
    public static int char2index(char ch) {
        int index = 0;
        if ('0' <= ch && ch <= '9') {
            index = ch - '0';
        } else if ('a' <= ch && ch <= 'z') {
            index = ch - 'a' + 10;
        } else if ('A' <= ch && ch <= 'Z') {
            index = ch - 'A' + 36;
        } else {
            index = -1;
        }
        
        return index;
    }
}

发表于 2018-02-11 11:18:57 回复(0)
#include <string>
#include <iostream>
using namespace std;
 
intmain()
{
    string a, need;
    intlength, length_need, *flag, *res, i, j, count = 0;
 
    cin >> a;
    cin.get();
    cin >> need;
 
    length = a.size();
    length_need = need.size();
    flag = newint[length];//记录a串中元素是否被实用过
    res = newint[length_need];
 
    for(i = 0; i < length; i++)
        flag[i] = 0;//初始化为0:未使用
    for(i = 0; i < length_need; i++)
        res[i] = 0;//need初始化为0:未买
 
    for(i = 0; i < length_need; i++)
    {
        for(j = 0; j < length; j++)
        {
            if(a[j] == need[i] && flag[j] == 0)
            {
                flag[j] = 1;
                res[i] = 1;//表示a中有此颜色
                break;
            }
        }
    }
 
    for(i = 0; i < length_need; i++)
    {
        if(res[i] == 1)
            count++;
    }
 
    if(count == length_need)
    {
        cout << "Yes "<< length - length_need;
    }
    else
    {
        cout << "No ";
        count = 0;
        for(i = 0; i < length_need; i++)
        {
            if(res[i] == 0)
                count++;
        }
        cout << count;
    }
    return0;
}
编辑于 2018-01-30 15:36:54 回复(0)
1.取定容器完成店家珠子存储
    tips:存储时需考虑map起先初始化无元素,map.get()会产生空指针异常。此时应该用 map.containsKey()进行判断。
2.遍历Eva珠子时,如果店家含有珠子则进行-1操作,如果不含该珠子就miss+1
    tips:需考虑店家原本有珠子,但是Eva遍历后变为0或者负,此时仍进行-1操作,无法进行miss+1
故需加上判0操作,如果店家珠子为0则进行miss+1
public class Main{
    public static void main(String[] args){
        Scanner input=new Scanner(System.in);
        String own=input.next();
        String Eva=input.next();
        int[] flag=new int[62];
        int miss=0;
        int rest=0;
        HashMap<Character,Integer> map=new HashMap();
        for(int i=0;i<own.length();i++){
            if(map.containsKey(own.charAt(i)))
                map.put(own.charAt(i),map.get(own.charAt(i))+1);
            else
                map.put(own.charAt(i),1);
        }
        for(int i=0;i<Eva.length();i++){
            if(map.containsKey(Eva.charAt(i))&&map.get(Eva.charAt(i))>0)
                map.put(Eva.charAt(i),map.get(Eva.charAt(i))-1);
            else
                miss++;
        }
        if(miss>0)
            System.out.print("No "+miss);
        else {
            Set set=map.keySet();
            Iterator iter= set.iterator();
            while(iter.hasNext()){
                rest+=map.get(iter.next());
            }
            System.out.print("Yes "+rest);
        }

    }
}


发表于 2021-02-26 14:29:40 回复(0)
#Python3
color=list(input())
aim=list(input())
asci=[0]*128
lack=0
for item in color:
    asci[ord(item)]+=1
for item in aim:
    asci[ord(item)]-=1
    if asci[ord(item)]<0:
        lack+=1
        
if lack<=0:
    print('Yes'+' '+str(len(color)-len(aim)))
else:
    print('No'+' '+str(lack))

发表于 2021-01-24 23:41:02 回复(0)
//第一次一遍就通过的问题
#include <iostream>
#include <string>
#include <map>
using namespace std;
map<char, int> cnt;
int main()
{
	string shop, eva;cin >> shop >> eva;
	for (int i = 0; i < shop.size(); ++i) cnt[shop[i]]++;
	for (int i = 0; i < eva.size(); ++i) cnt[eva[i]]--;
	bool isOK = true; int miss = 0, extra = 0;
	int i;
	for (i = 0; i < eva.size(); ++i) {
		if (cnt[eva[i]] < 0) {
			isOK = false; miss -= cnt[eva[i]];
		}
		else extra += cnt[eva[i]];
		cnt[eva[i]] = 0;
	}
	if (isOK)for (i = 0; i < shop.size(); ++i)extra += cnt[shop[i]];
	if (isOK)cout << "Yes " << extra;
	else cout << "No " << miss;
	return 0;
}



发表于 2020-12-03 08:57:36 回复(0)
//
#include<iostream>
(720)#include<vector>
#include<string>
using namespace std;
int main() {
	string needs, shop_owner;
	cin >> shop_owner;
	cin >> needs;
	int number1[128] = { 0 };
	int number2[128] = { 0 };
	for (int i = 0; i < needs.size(); i++) {
		number1[needs[i]]++;
	}
	for (int i = 0; i < shop_owner.size(); i++) {
		number2[shop_owner[i]]++;
	}
	int yes = 0, no = 0;
	bool flag = true;
	for (int i = 0; i < 128; i++) {
		if (number1[i]) {
			if (number2[i] >= number1[i]) {
				yes += number2[i] - number1[i];
			}
			if (number2[i] < number1[i]) {
				flag = false;
				no+= number1[i] - number2[i];
			}
		}
		else {
			yes += number2[i];
		}
	}
	if (flag) { printf("Yes %d", yes); }
	else { printf("No %d", no); }
}


发表于 2020-03-21 13:23:10 回复(0)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {     string buy, sell;     cin >> sell >> buy;     int neednum;     neednum = 0;     for (auto tmp : buy) {         for (int i = 0; i < sell.size();++i) {             if (tmp == sell[i]) {                 sell[i] = '/';                 ++neednum;                 break;             }         }     }     if (neednum == buy.size()) {         cout << "Yes"<<" "<<sell.size() - neednum << endl;         //return 0;     }     else {         cout << "No"<<" "<<buy.size() - neednum << endl;         //return 0;     }     //system("pause");
}

发表于 2019-06-05 19:50:26 回复(0)
/* https://www.nowcoder.com/pat/5/problem/4038  To Buy or Not to Buy (20)   2018-12-20
 General mean: Give you two string 'have' and 'need', reponse if "have" have all the char
 in "need" ,and how many surpule or own.
 Result: Dont need to say, a simple question. 
 */
 #include"stdafx.h"
 #include<iostream>
 #include<string.h>
 #include<string>
 using namespace std;
 string have, need;
 int temp[1000];
 int main(){
     int own = 0;
     cin >> have >> need;
     for (int i = 0; i < have.length(); i++) temp[(int)have[i]]++;
     for (int i = 0; i < need.length(); i++){
         if (temp[(int)need[i]] <= 0) own++;
         else temp[(int)need[i]]--;
     }
     if(own<=0)cout << "Yes " << have.length() - need.length() << endl;
     else cout << "No " << own << endl;
     return 0;
 }
发表于 2018-12-20 20:04:40 回复(0)
boo,con,con1 = True,0,0
nlst,mlst = [],[]
n = input()
m = input()
for i in n:
    nlst.append(i)
for j in m:
    mlst.append(j)
ms = list(set(mlst))
for i in ms:
    if i not in n:
        boo = False
        con+=m.count(i)
    else:
        if n.count(i)<m.count(i):
            boo = False
            con+=m.count(i) - n.count(i)
if boo:
    print("Yes "+str(len(nlst)-len(mlst)))
else:
    print("No "+str(con))

发表于 2018-12-07 21:26:14 回复(0)

//注意如果够则输出剩余珠子
//不够也输出不够的珠子的个数

import java.io.*;
public class Main {

public static void main(String[] args)throws IOException
{
    int flag=0;
    int j;
    int temp;
    BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
    StringBuffer first_String=new StringBuffer(reader.readLine());
    StringBuffer second_String=new StringBuffer(reader.readLine());
    for(int i=0;i<second_String.length();i++)
    {
        temp=0;
        for( j=0;j<first_String.length();j++)
        {
            if(second_String.charAt(i)==first_String.charAt(j))
            {
                first_String.delete(j,j+1);
                temp=1;
                break;
            }
        }
        if(temp==0)
        {
            flag++;

        }

    }
    if(flag ==0)
    {
        System.out.print("Yes "+first_String.length());
    }
    else

    {
        System.out.print("No "+flag);
    }




}

}

发表于 2018-10-09 22:13:07 回复(0)
#include "stdafx.h"
#include <cstdio>

int hashTable[128] = {0};
bool more = true;
int main(){     char c;     while((c = getchar()) != '\n'){         hashTable[c]++;     }     while((c = getchar()) != '\n'){         hashTable[c]--;         if(hashTable[c] < 0)more = false;     }     int cnt = 0;     for(int i = 0; i < 128; ++i){         if(more){             cnt += hashTable[i];         }else{             if(hashTable[i] < 0)cnt += -hashTable[i];         }     }     if(more)printf("Yes %d\n", cnt);     else printf("No %d\n", cnt);     return 0;
}

发表于 2018-07-27 16:37:55 回复(0)
//map即可
#include <bits/stdc++.h>
using namespace std;
map<int,int> mp1,mp2;
int main(){
    string str1,str2;int miss=0;
    cin>>str1>>str2;
    for(const auto &ch:str1) ++mp1[ch];
    for(const auto &ch:str2) ++mp2[ch];
    for(const auto &ch:mp2){
        if(mp1[ch.first]<ch.second) miss+=ch.second-mp1[ch.first];
    }
    if(!miss) cout<<"Yes "<<str1.size()-str2.size()<<endl;
    else cout<<"No "<<miss<<endl;
    return 0;
}

发表于 2018-03-11 22:29:16 回复(0)
#include<iostream>
#include<string>
using namespace std;
int main(){
 string have,want,tmp;
 cin>>have>>want;
 tmp=have;
 int lack;
 lack=0;
 for(int i=0;i<want.size();i++){
  if(int(tmp.find(want[i],0))==-1){
   lack++;
  }else{
   tmp.erase(tmp.find(want[i],0),1);
  }
 }
 if(lack!=0)
  cout<<"No "<<lack<<endl;
 else
  cout<<"Yes "<<tmp.size()<<endl;
 return 0;
}
发表于 2017-02-18 19:25:30 回复(0)
import java.util.Scanner;
public class Main{
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		int[] c=new int[256];
		char[] a=in.next().toCharArray();
		char[] b=in.next().toCharArray();
		for(int i=0;i<b.length;i++){
			c[b[i]]++;
		}
		for(int i=0;i<a.length;i++){
			c[a[i]]--;
		}
		int count=0;
		boolean flag=true;
		for(int i=0;i<b.length;i++){
			if(c[b[i]]>0){
				count+=c[b[i]];
				flag=false;
				c[b[i]]=0;
			}
		}
		if(flag){
			System.out.println("Yes "+(a.length-b.length));
		}else{
			System.out.println("No "+count);
		}
	}
}

发表于 2017-02-02 12:11:44 回复(0)
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=1005;
int cnt[256];
char str1[maxn],str2[maxn];
int main(){
    //freopen("in.txt","r",stdin);
    scanf("%s%s",str1,str2);
    int len1=strlen(str1),ans=0;
    for(int i=0;i<len1;i++){
        cnt[str1[i]]++;
    }
    bool ok=true;
    int len2=strlen(str2);
    for(int i=0;i<len2;i++){
        if(cnt[str2[i]]==0){
            ok=false;
            ans++;
        }
        else{
            cnt[str2[i]]--;
        }
    }
    if(ok){
        printf("Yes %d\n",len1-len2);
    }
    else{
        printf("No %d\n",ans);
    }
    return 0;
}

发表于 2016-08-04 01:41:05 回复(0)
#include<stdio.h>
#include<string.h>
int main()
{
char str1[1001],str2[1001];
    scanf("%s %s",str1,str2);
    int i,j;
    for(i=0;i<strlen(str1);i++)
    {
    for(j=0;j<strlen(str2);j++)
        {
        if(str1[i]==str2[j])
            {
            str1[i]='*';
                str2[j]='*';
            }
        }
    }
    for(i=0;i<strlen(str2);i++)
    {
    if(str2[i]!='*')
        {
        break;    
        }
    }
    if(i==strlen(str2))
    {
        int count=0;
    for(i=0;i<strlen(str1);i++)
        {
        if(str1[i]!='*')
            {
            count++;
            }
        }
        printf("Yes %d",count);
    }
    else
    {
        int count1=0;
    for(i=0;i<strlen(str2);i++)
        {
            if(str2[i]!='*')
            {
            count1++;    
            }
        }
        printf("No %d",count1);
    }
    return 0;
}
发表于 2016-01-18 09:28:49 回复(0)

问题信息

难度:
20条回答 10603浏览

热门推荐

通过挑战的用户

To Buy or Not to Buy (20)