首页 > 试题广场 >

到底买不买(20)

[编程题]到底买不买(20)
  • 热度指数:10812 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
小红想买些珠子做一串自己喜欢的珠串。卖珠子的摊主有很多串五颜六色的珠串,但是不肯把任何一串拆散了卖。于是小红要你帮忙判断一
下,某串珠子里是否包含了全部自己想要的珠子?如果是,那么告诉她有多少多余的珠子;如果不是,那么告诉她缺了多少珠子。

为方便起见,我们用[0-9]、[a-z]、[A-Z]范围内的字符来表示颜色。例如,YrR8RrY是小红想做的珠串;那么ppRYYGrrYBR2258可以买,因为包含了
全部她想要的珠子,还多了8颗不需要的珠子;ppRYYGrrYB225不能买,因为没有黑色珠子,并且少了一颗红色的珠子。

输入描述:
每个输入包含1个测试用例。每个测试用例分别在2行中先后给出摊主的珠串和小红想做的珠串,两串都不超过1000个珠子。


输出描述:
如果可以买,则在一行中输出“Yes”以及有多少多余的珠子;如果不可以买,则在一行中输出“No”以及缺了多少珠子。其间以1个空格分隔。
示例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:08:48 回复(3)

一点点在线处理

#include <stdio.h>
int main(){
 char A[123] = {0}, B[123] = {0}, i, rest = 0, count_A = 0, count_B = 0, ch;
 while ((ch = getchar()) != '\n')
  A[ch]++,count_A++;
 while ((ch = getchar()) != '\n')
  B[ch]++,count_B++;
 for (i = 1; i < 123; i++)
  if (B[i] != 0)
   rest += (A[i] >= B[i] ? 0 : B[i] - A[i]);
 if (rest != 0)
  printf("No %d", rest);
 else
  printf("Yes %d", count_A - count_B);
}

发表于 2017-08-08 23:58:25 回复(0)
public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String oldStr = sc.nextLine();
        String needStr = sc.nextLine();

        Map<Character,Integer> map = new HashMap<>();
        char[] chars = oldStr.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (map.containsKey(chars[i])){
                int count = map.get(chars[i]);
                map.put(chars[i],count+1);
            }else {
                map.put(chars[i],1);
            }
        }

        char[] needChars = needStr.toCharArray();
        int lastCount = 0;
        for (int i = 0; i < needChars.length; i++) {
            if (map.containsKey(needChars[i])){
                if (map.get(needChars[i])>0){
                    int count = map.get(needChars[i]);
                    map.put(needChars[i],count-1);
                }else {
                    lastCount++;
                }
            }else {

                lastCount++;
            }
        }

        if (lastCount==0){
            System.out.println("Yes "+(oldStr.length()-needStr.length()));
        }else {
            System.out.println("No "+lastCount);
        }

    }
发表于 2018-01-31 20:17:07 回复(0)
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
unordered_map<char,int> book;
int main(){
    ios::sync_with_stdio(false);
    string s1,s2;
    cin>>s1>>s2;
    int extra = 0,flag = 0;
    for(char c : s1) book[c]++;
    for(char c : s2){
        if(book[c]>0) book[c]--;
        else extra++,flag = 1;
    }
    flag ? cout<<"No "<<extra<<endl:cout<<"Yes "<<s1.length()-s2.length()<<endl;
    return 0;
}

发表于 2019-04-28 14:20:46 回复(0)
思路:通过一个ArrayList保存摊主有的珠子,然后在循环查询小红想买的珠子,如果摊主的珠串上有该颜色,则将ArrayList中该下标
的颜色珠子移除,再查找剩余的颜色珠子。
特别注意:输出格式“No”,不要输出“NO”!!!
import java.util.*;
 
publicclassMain{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str1 = sc.next();
            String str2 = sc.next();
            LinkedList<Character> list = new LinkedList<Character>();
            for(inti = 0; i < str1.length(); i++){
                charch = str1.charAt(i);
                list.add(ch);
            }
            int count = 0;
            for(inti = 0; i < str2.length(); i++){
                charch = str2.charAt(i);
                for(intj = 0; j < list.size(); j++){
                    if(ch == list.get(j)){
                        list.remove(j);
                        count++;
                        break;
                    }
                }
            }
            if(count == str2.length())
                System.out.println("Yes "+ (str1.length()-count));
            else
                System.out.println("No "+ (str2.length()-count));
        }
        sc.close();
    }   
}

编辑于 2017-12-16 15:10:57 回复(1)
#计算想要的珠子集合里,想要的和已有的数量谁多,想要的多的话就是缺失
#有缺失输出No,否则输出Yes
try:
    while True:
        have = input()
        want = input()
        lost = 0
        for i in set(want):
            if have.count(i) < want.count(i):
                lost += want.count(i)-have.count(i)
        if lost:
            print('No %d'%lost)
        else:
            print('Yes %d'%(len(have)-len(want)))

except Exception:
    pass

编辑于 2018-11-18 20:58:01 回复(0)
超短
#include<bits/stdc++.h>
#define maxn 1000
using namespace std;
int main(){
    char a[maxn],b[maxn];
    int count=0,need[128]={0};
    scanf("%s%s",&a,&b);
    for(int i=0;i<strlen(a);need[a[i++]]++);
    for(int j=0;j<strlen(b);need[b[j]]--,need[b[j]]<0?count++,j++:j++);
    (count>0)?printf("No %d",count):printf("Yes");
}

编辑于 2018-06-17 11:49:49 回复(0)
#include<stdio.h>
#include<string.h>
int main (){//the shorter,the better.
    int hash[128],i,l[2];char need[1000],sell[1000];
    for(;~scanf("%s %s",sell,need);printf(l[1]>0?"No %d\n":"Yes %d\n",l[l[1]>0])){
        for(memset(hash,0,sizeof(hash)),l[0]=strlen(sell),i=0;i<l[0];++hash[sell[i]],i++);
        for(l[1]=strlen(need),i=0;i<l[1];--hash[need[i]],i++);
        for(l[0]=l[1]=i=0;i<128;hash[i]<0?(l[1]+=-hash[i]):(l[0]+=hash[i]),i++);
    }
}

发表于 2018-01-29 17:56:52 回复(0)
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String a = in.next();
		String my = in.next();
		int[] arr = new int[62];
		for(int i = 0;i<my.length();i++)
			arr[index(my.charAt(i))]++;
		for(int i = 0;i<a.length();i++)
			arr[index(a.charAt(i))]--;
		int need = my.length();
		int miss = 0;
		for(int i = 0;i<my.length();i++){
			int index = index(my.charAt(i));
			if(arr[index]<=0)
				need--;
			else{
				miss += arr[index];
				arr[index] = 0;
			}
		}
		if(need==0){
			need = 0;
			for(int i = 0;i<arr.length;i++){
				if(arr[i]<0)
					need += -arr[i];
			}
			System.out.println("Yes"+" "+need);
		}else {
			System.out.println("No"+" "+miss);
		}
			
	}
	private static int index(char c){
		if(c>='a'&&c<='z')
			return c-'a';
		if(c>='A'&&c<='Z')
			return 26+c-'A';
		if(c>='0'&&c<='9')
			return 26+26+c-'0';
		return -1;
	}
}
pat的题快做完了,发现很多人都喜欢调用api,是很方便,但是看看源码就知道这样做效率很低了
编辑于 2016-06-12 14:46:17 回复(0)
#include <cstdio>
int main() {
    for (int c,step = 1, hash[128] = {0}, sum = 0, lack = 0; step == 1 ? ((c = getchar()) != '\n'?(++hash[c] + ++sum):(step = 2)):((c = getchar()) != '\n'?(--hash[c] < 0 ? ++lack : --sum):(!lack ? ~printf("Yes %d", sum) : ~printf("No %d", lack))) > 0;);
    return 0;
}


编辑于 2021-10-11 19:59:51 回复(0)
#include<iostream>
#include<string>
using namespace std;

int main(){
    ios::sync_with_stdio(false);  // 提高了速度
    
    int sign ,hash[123] = {0};
    string str_good, str_need;
    sign = 0;
    cin>>str_good>>str_need; 
    
    for(char c : str_good) hash[c]++; 
    for(char c : str_need)
        if(hash[c])
            hash[c]--;
        else
            sign++;
    cout<<(sign?"No": "Yes")<<" "<<(sign?sign:str_good.size() - str_need.size());
   return 0;
}

发表于 2020-10-31 21:47:59 回复(0)
这种题嘛,最基础的方法就是放数组里遍历最方便了
#include <iostream>
using namespace std;
 
int main()
{
    int sold[75] = {0};
    int buy[75] = {0};
    int flag = 1, more = 0, less = 0;
    string solder, buyer;
    cin >> solder >> buyer;
    for(int i = 0; i < solder.length(); i++)
        sold[solder[i]-48]++;
    for(int i = 0; i < buyer.length(); i++)
        buy[buyer[i]-48]++;
     
    for(int i = 0; i < 75; i++){
        if(buy[i]!=0){
            if(sold[i]<buy[i]) flag = 0;
            if(buy[i]-sold[i]>0) less += buy[i]-sold[i];
        }
        if(sold[i]-buy[i]!=0)
            more += sold[i]-buy[i];
    }
     
    if(flag) cout << "Yes " << more;
    else cout << "No " << less;
    return 0;
}


发表于 2020-02-12 14:54:40 回复(0)
 
import java.util.HashMap;
import java.util.Scanner;

public class PAT29 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        HashMap<Character, Integer> map = new HashMap<>();
        String sample = scanner.next();
        String target = scanner.next();
        int length = sample.length();
        for (int i = 0; i < length; i++) {
            map.merge(sample.charAt(i), 1, Integer::sum);
        }
        int targetLen = target.length();
        int leak = 0;//缺少
        char ch;
        for (int i = 0; i < targetLen; i++) {
            ch = target.charAt(i);
            Integer value = map.get(ch);
            if (value == null || value == 0) {
                leak++;
            }else {
                map.put(ch, value-1);
            }
        }
        if (leak == 0) {
            System.out.println("Yes " + (length - targetLen));
        } else {
            System.out.println("No " + leak);
        }
        scanner.close();
    }
}

发表于 2019-08-09 17:30:10 回复(0)
import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        List<Character>list1=new ArrayList<>();
        List<Character>list2=new ArrayList<>();
        String s1=in.next();
        String s2=in.next();
        for(char c:s1.toCharArray())
        {
            list1.add(c);
        }
        for(char c:s2.toCharArray())
        {
            list2.add(c);
        }
        int count=0;
        for(char c2:list2) {
            for(char c1:list1) {
                if(c2==c1) {
                    list1.remove(list1.indexOf(c1));
                    count++;
                    break;
                }
            }
        }
        if(count==list2.size()) {
            System.out.print("Yes"+" "+(s1.toCharArray().length-list2.size()));
        }
        else
             System.out.print("No"+" "+(list2.size()-count));
    } 
}


发表于 2019-04-29 17:40:40 回复(0)
//思路:不用直接去比较,直接比较商家和顾客相同颜色珠子的个数即可
//先计算得到商家有哪些珠子,且每种颜色的珠子各有多少个,同理得到顾客需要的珠子的情况
//之后以顾客为目标去商家手里面找,是不是有满足条件的珠子,如果有,个数是否对,个数不对则计算差多少个,如果没有则直接得到当前差值,依次处理每个颜色的珠子,直到结束。
#include<iostream>
#include<string>
#include<map>
#include<cmath>

using namespace std;

int main()
{
    string str;   //商人的珠子
    string str2;  //顾客的珠子
    cin >> str;
    cin >> str2;
    
    map<char, int> data_saler;
    map<char, int> data_buyer;
    //统计一下商家的珠子的个数
    for (int i = 0; i < str.length(); i++)
    {
        int count = 0;
        for (int j = i + 1; j < str.length(); j++)
        {
            if (str[i] == str[j])
            {
                count++;
            }
        }
        data_saler.insert({ str[i],count + 1 });
    }


    //统计一下顾客的珠子的个数
    for (int i = 0; i < str2.length(); i++)
    {
        int count = 0;
        for (int j = i + 1; j < str2.length(); j++)
        {
            if (str2[i] == str2[j])
            {
                count++;
            }
        }
        data_buyer.insert({ str2[i],count + 1 });
    }

    //以顾客为目标查找商家各个珠子的数目是否满足顾客的需求
    int flag = 1;
    int chazhi = 0;
    for (auto iter = data_buyer.begin(); iter != data_buyer.end(); iter++)
    {
        auto iter_tmp = data_saler.find(iter->first);
        if (iter_tmp != data_saler.end())  //如果有这种颜色的珠子
        {
            if (iter_tmp->second >= iter->second)    //如果有这种颜色的珠子,且个数满足要求,则该种颜色置为1,后面如有不满足的则标志为置0;
            {
                flag = 1 & flag;
            }
            else
            {
                flag = 0 & flag;
                chazhi = chazhi + (iter->second - iter_tmp->second);
            }
        }
        else
        {
            flag = 0;
            chazhi = chazhi + iter->second;
        }
    }

    if (flag == 1)
    {
        cout << "Yes" << " " << str.length() - str2.length() << endl;
    }
    else
        cout << "No" << " " << chazhi << endl;
    system("pause");
    return 0;
}

发表于 2019-04-12 18:13:39 回复(0)
主要满足两个功能,一是判断是否s1中可以匹配s2中所有字母(s1中已经与s2匹配到的不参与再次匹配),二是统计s1中多余字符的数目或者s2中未匹配字符的数目
编辑于 2018-07-20 13:11:28 回复(0)
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string S1, S2;
    int a = 0;
    bool buy = true;
    cin >> S1 >> S2;
    for (int i = 0; i<S2.size(); i++)
    {
        if (S1.find(S2[i]) != string::npos)
            S1.erase(S1.find(S2[i]), 1);
        else {
            buy = false;
            a++;
        }
    }
    if (buy == true)
        cout << "Yes" << ' ' << S1.length();
    else
        cout << "No" << ' ' << a;
    system("pause");
    return 0;
}
发表于 2018-05-24 21:33:55 回复(0)
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;


public class Main{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		boolean weatherBy = true;
		int lack = 0;
		int redundant = 0;
		Scanner sc = new Scanner(System.in);
		String have = sc.nextLine();
		String need = sc.nextLine();
		Map <Character,Integer> h = new HashMap<>();
		Map <Character,Integer> n = new HashMap<>();
		for (char c:have.toCharArray()) {
			if(h.containsKey(c)){
				h.put(c, h.get(c)+1);
			}else{
				h.put(c, 1);
			}
		}
		for (char c : need.toCharArray()) {
			if(n.containsKey(c)){
				n.put(c, n.get(c)+1);
			}else{
				n.put(c, 1);
			}
		}
		Iterator<Entry<Character, Integer>> it = n.entrySet().iterator();
		while(it.hasNext()){
			Entry<Character, Integer> en = it.next();
			char k = en.getKey();
			int v = en.getValue();
			if(h.containsKey(k) && h.get(k)<v){
				weatherBy = false;
				lack += v -h.get(k);
			}else if(! h.containsKey(k)){
				weatherBy = false;
				lack += v;
			}
		}
		if(weatherBy == true){
			System.out.println("Yes "+(have.length()-need.length()));
		}else{
			System.out.println("No "+lack);
		}
	}

}

编辑于 2017-08-20 21:14:55 回复(0)

#include<iostream>
#include<string>
using namespace std;
 
// PAT乙级到底买不买(20)
 
intmain()
{
    string str1,str2;
    cin>>str1>>str2;
    intstr1length=str1.length();
    intstr2length=str2.length();
    inti,j,num1=0,num2=0;
    for(i=0;i<str1length;i++){
        for(j=0;j<str2length;j++){
            if(str1[i]==str2[j]){
                str1[i]='#';
                str2[j]='#';
                continue;
            }
        }
    }
    //caculate the str1 remanding number
    for(i=0;i<str1length;i++){
        if(str1[i]!='#')
            num1++;
    }
    //caculate the str1 remanding number
    for(j=0;j<str2length;j++){
        if(str2[j]!='#')
            num2++;
    }
    //num2 > 0 suggests str1 is lack of some number,output the num2
    //else  output num1
    if(num2)
        cout<<"No "<<num2<<endl;
    else
        cout<<"Yes "<<num1<<endl;
    return0;
}

发表于 2017-01-15 17:02:24 回复(1)
#include <iostream> 
using namespace std;
int main()
{
	char a[1000] = { 0 };
	char b[1000] = { 0 };
	cin >> a >> b;
	int remain = 0;
	int k;
	int n = 0;
	int m = 0;
	for (int i = 0; b[i] != '\0'; i++)
	{
		n++;
		k = 0;
		for (int j = 0; a[j] != '\0'; j++)
		{
			m++;
			if (a[j] == b[i])
			{
				k = 1;
				a[j] = '*';
				break;
			}
		}
		if (k == 0)
			remain++;
	}
	if (remain == 0)
		cout << "Yes" << " " << m / n - n;
	else cout << "No" << " " << remain;
	return 0;
}
编辑于 2016-10-17 22:30:41 回复(0)