2014NOIP普及组真题 1. 珠心算测验

线上OJ:

一本通:http://ybt.ssoier.cn:8088/problem_show.php?pid=1965

核心思想:

1、题目所求为"有多少个数=其他两个数之和 ",故不管5是由1+4组成,还是2+3组成,都只算一次。

2、利用 set自动去重 的功能,只要将结果丢进set,最后输出set的size即可

3、由于题目的 n 只有100,非常小,所以可以用三重循环暴力枚举直接完成

cpp 复制代码
#include <bits/stdc++.h>
#define MAXN 105
using namespace std;

set<int> s; // 利用set有自动去重的功能,只要将结果丢进set,最后输出set的size即可
int n;
int a[MAXN];

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++)  cin >> a[i];

    for(int i = 1; i <= n; i++)
        for(int j = i + 1; j <= n; j++)
            for(int k = 1; k <= n; k ++)
            {
                if(a[i]+a[j]==a[k])
                {
                    s.insert(a[k]);
                }
            }

    cout << s.size() << endl;
    return 0;
}
思考:

如果 n 的范围超过 1 0 3 10^3 103,则上述方法会超时,这是可以考虑反向枚举答案 ,因为a[i]不超过10,000,所以最终的和不超过20000。只要 建20000个桶,最后看哪些桶的结果被标记过了即可

cpp 复制代码
#include <bits/stdc++.h>
#define MAXN 105
using namespace std;

int n, ans = 0;
int a[MAXN];
int res[20005] = {0};

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++)  cin >> a[i];

    for(int i = 1; i <= n; i++)
        for(int j = i + 1; j <= n; j++)
            res[a[i] + a[j]] = 1; // 标记为计算过

    for(int i = 1; i <= n; i++)
        if(res[ a[i] ]) ans++;   // 如果a[i]数组中的值在res[i]被标记过,则ans++

    cout << ans << endl;
    return 0;
}
相关推荐
老四啊laosi1 天前
[C++进阶] 24. 哈希表封装unordered_map && unordered_set
c++·哈希表·封装·unordered_map·unordered_set
2301_764441331 天前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI1 天前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
妙为1 天前
银河麒麟V4下编译Qt5.12.12源码
c++·qt·国产化·osg3.6.5·osgearth3.2·银河麒麟v4
Billlly1 天前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives1 天前
atcoder ABC 452 题解
数据结构·算法
feifeigo1231 天前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
fengfuyao9851 天前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
无敌昊哥战神1 天前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
小白菜又菜1 天前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展