0
点赞
收藏
分享

微信扫一扫

ktv问题

题目来源:赛码网基础算法
题目描述:有n个人去KTV唱歌,每个人都有自己想唱的一些歌。已经该KTV每个房间有x个麦克风,同一首歌可以大家一起唱,但是同时唱的人不能超过x,同一时刻只能唱一首歌,一共有y首歌的时间。所有人把想唱的歌唱完或者y首歌唱完就会离开。他们想知道在最优的安排策略下,当他们离开时是否有人还没唱,输入保证每个人想唱的歌都不同。

输入描述:
第一行整数代表测试的组数;
第二行的第三个数分别表示有几个人(n)、麦克风的数量(x)和点歌的总数(y)
接下来的n行中,第一个数字表示第i个人想唱的数量m,后面的m个数,表示他想唱的歌曲编号
输出描述:
如果在走之前所有人都唱了自己想唱的歌,输出yes,否则输出no。

样例:

元素输入
测试次数1
n/x/y的数值3 3 3
第一个人想唱的歌的总数和编号1 2
第二个人想唱的歌的总数和编号1 2
第三个人想唱的歌的总数和编号1 3

此时,三个人共唱三首歌,且每首歌不会超过3个人唱,也就是这样的分配情况下,只需要两首歌的时间就能解决战斗离开KTV,所以输出yes。

分析
完成程序基本框架:循环测试组数,每一组输入n/x/y值以及采集到每个人唱歌的情况。考虑到最后是判断唱歌的次数不会超过之前给定的y值,所以可以将之前得到的每个人唱的歌曲编号放在一个键值对里面(前面的文章讲到了键值对的好处)。然后统计最少唱几次就能唱完全部歌曲,最少的次数是每首歌在麦克风满足的情况下最多人都在同时唱,然后和之前的歌曲数目y比较就可以得到最终的结果。

代码如下

// n个人去KTV,每个人都有想唱的歌,,每个房间x个麦克风,共y首歌的时间
// 第一行一个整数表示数据组数
// 第二行表示n, x, y
// 接下来n行从上到下表示1 - n个人的想唱的歌,第一个数是唱的数量,后面是歌的编号,编号不大于1000
// 输出yes表示都唱了,no表示没有唱完
#include <iostream>
#include <vector>
#include <unordered_map>
#include <cmath>

using namespace std;

int main()
{
    int group;
    cout << "Enter the number of group: ";
    cin >> group;
    while(group--)
    {
        int n, x, y;
        cout << "Enter the number of people, the number of microphones, and the number of songs: ";
        cin >> n >> x >> y;
        if(y > 1000)
        {
            cout << "Too many songs you want to sing!" << endl;
            continue;
        }
        // cout << "n = " << n << " ,x = " << x << " ,y = " << y << endl;
        cout << "Enter the songs you want to sing, and the serial number of the song: " << endl;
        vector<int> songs;
        for(int i = 0; i < n; i++)
        {
            int num;
            cin >> num;
            for(int j = 0; j < num; j++)
            {
                int song;
                cin >> song;
                songs.push_back(song);
            }
        }
        /*
        cout << "the elemnts of songs: ";
        for(int i = 0; i < songs.size(); i++)
        {
            
            cout << songs[i] << " ";
        }
        cout << endl;
        */
        unordered_map<int, int> song_map;
        for(int i = 0; i < songs.size(); i++)
        {
            song_map[songs[i]]++;
        }
        /*
        // 键值对map里的内容
        cout << "the elemnts of song_map: ";
        for(int i = 0; i < song_map.size(); i++)
        {
            cout << song_map[i] << " ";
        }
        cout << endl;
        */
        // 求唱歌的总的数量
        int count = 0;
        for(int i = 0; i < song_map.size(); i++)
        {
            if(song_map[i] > x)
            {
                count += ceil(song_map[i] / x);
            }
            else if(song_map[i] > 0)
            {
                count++;
            }
        }
        // cout << "count = " << count << endl;
        if(count > y)
        {
            cout << "no" << endl;
        }
        else{
            cout << "yes" << endl;
        }
    }
    return 0;
}

程序最终的运行结果为:
在这里插入图片描述

举报

相关推荐

0 条评论