博客
关于我
【PAT】1124 Raffle for Weibo Followers (20 分)
阅读量:739 次
发布时间:2019-03-22

本文共 1275 字,大约阅读时间需要 4 分钟。

为了生成John的幸运观众列表,我们可以采用以下策略:

  • 读取输入数据:首先,读取N、step和first的值,然后读取每个粉丝的名字存入向量followers。

  • 初始化结构:使用vector来存储粉丝名字,并使用map来记录每个粉丝被抽中的次数,以避免重复抽选。

  • 抽奖循环:从指定的起始位置开始,每隔step个单位抽取一个粉丝。如果已经被抽中过,无需再次抽选,继续到下一个位置。

  • 更新结果:每次抽到一个新的粉丝时,将名字添加入winners向量,并将其计数加一,以便下一次抽取时跳过。

  • 处理结果:最后输出所有幸运观众的名字,或提示如果没有人中奖。

  • 以下是优化后的代码:

    #include 
    #include
    #include
    #include
    #include
    using namespace std;int main() { int n, step, first; string f; vector
    followers; vector
    winners; map
    record; scanf("%d %d %d", &n, &step, &first); for (int i = 0; i < n; i++) { cin >> f; followers.push_back(f); } int i = first - 1; // 从第first位开始 while (i < n) { int current = i; while (true) { string current_follower = followers[current]; if (record.find(current_follower) == record.end()) { break; } else { current += step; if (current >= n) { i = n; // 结束循环 break; } } } if (current >= n) break; i = current; winners.push_back(followers[current]); record[followers[current]]++; } if (winners.empty()) { cout << "Keep going...\n"; } else { for (const auto& winner : winners) { cout << winner << endl; } } return 0;}

    知识点总结:

    • set和unordered_set:set按字典序排列,unordered_set元素存储位置随机,无法保证顺序。
    • reverse()函数:用于逆转向量。
    • 效率选择:使用向量存储粉丝,通过常见结构(如map)记录抽奖次数,确保高效且避免重复抽选,不影响查询和修改性能。

    转载地址:http://cgjwk.baihongyu.com/

    你可能感兴趣的文章
    Python 内嵌函数:它们有什么用处?
    查看>>
    Python 基础语法:基本数据类型(集合)
    查看>>
    python 复习计划
    查看>>
    Python 多处理 apply_async 永远不会在 Windows 7 上返回结果
    查看>>
    Python 多处理 Numpy 随机
    查看>>
    Python 多处理 >= 125 列表永远不会完成
    查看>>
    Python 多处理:在第一个子错误时中止映射
    查看>>
    Python 多处理不断产生 pythonw.exe 进程而不做任何实际工作
    查看>>
    Python 多处理从不加入
    查看>>
    Python 多处理如何优雅地退出?
    查看>>
    Python 多处理将子进程的标准输出重定向到 Tkinter 文本
    查看>>
    Python 多处理库错误(AttributeError:__exit__)
    查看>>
    Python 多处理模块的 .join() 方法到底在做什么?
    查看>>
    python 多线程与GIL
    查看>>
    Python 字符串总结
    查看>>
    python 字符串显示中文_Python字符串开头的b"、u"、r"与中文乱码
    查看>>
    Python 字符串的几种拼装方式
    查看>>
    python 存入数据库bigint_python基础_MySQL的bigint类型
    查看>>
    python 学习 面向对象编程
    查看>>
    Python 安装程序:“写入文件 C:\Python27\pythonw.exe 时出错“
    查看>>