10474 - Where is the Marble?

本文解析了UVA 10474 Marble Game问题,介绍了通过C++实现排序和查找的解决方案。该方案首先读取一组数字并将其排序,然后根据查询输出每个数字的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:
读入一行2个数字 N 和 Q, N 表示接下来的 N 行数字为 marbles, Q 表示 N 行数字之后的 Q 行数字为 query. 要求把 N 行 marbles 从小到大排序, 然后输出每个 Q 在 marbles 中的位置.

思路:
把读入的 marbles 和 queries 都存放在 vector 里, 然后排序, 再逐个查找进行输出即可.

要点:
使用 sort(marbles.begin(), marbles.end(), less<int>()); 从小到大进行排序.

题目:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=98&page=show_problem&problem=1415

代码:

# include <iostream>
# include <string>
# include <cstdio>
# include <cstring>
# include <vector>
# include <algorithm>
# include <cctype>
# include <iterator>
# include <assert.h>
using namespace std;

// 使用 sort 排序

int main(int argc, char const *argv[])
{
  #ifndef ONLINE_JUDGE
    freopen("10474_i.txt", "r", stdin);  
    freopen("10474_o.txt", "w", stdout); 
  #endif
  
  int numCase = 0;

  while (!cin.eof()) {
    int numMarbles;
    int numQueries;
    cin >> numMarbles >> numQueries;

    if (numMarbles == 0 && numQueries == 0)
      break;

    cout << "CASE# " << ++numCase << ":" << endl;

    vector<int> marbles;
    vector<int> queries;
    int temp;

    for (int i=0; i<numMarbles; i++) {
      cin >> temp;
      marbles.push_back(temp);
    }
    for (int i=0; i<numQueries; i++) {
        cin >> temp;
        queries.push_back(temp);
    }

    sort(marbles.begin(), marbles.end(), less<int>());

    for (int i=0; i<numQueries; i++) {
      vector<int>::iterator it = find(marbles.begin(), marbles.end(), 
                                      queries[i]);
      if (it == marbles.end()) {
        cout << queries[i] << " not found" << endl;
      } else {
        cout << queries[i] << " found at " << it - marbles.begin() + 1 << endl;
      }
    }
  } // end of while

  return 0;
}

环境: C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE

转载于:https://my.oschina.net/zenglingfan/blog/146531

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值