题解 | Costume Party-牛客假日团队赛8H题

H-Costume Party_牛客假日团队赛8

https://ac.nowcoder.com/acm/contest/1069/H

题目描述

It's Halloween! Farmer John is taking the cows to a costume party, but unfortunately he only has one costume. The costume fits precisely two cows with a length of . FJ has N cows conveniently numbered 1..N; cow i has length . Two cows can fit into the costume if the sum of their lengths is no greater than the length of the costume. FJ wants to know how many pairs of two distinct cows will fit into the costume.

输入描述:

* Line 1: Two space-separated integers: N and S
* Lines 2..N+1: Line i+1 contains a single integer:

输出描述:

* Line 1: A single integer representing the number of pairs of cows FJ can choose. Note that the order of the two cows does not matter.

示例1

输入
4 6
3
5
2
1
输出
4
说明
The four pairs are as follows: cow 1 and cow 3; cow 1 and cow 4; cow 2 and cow 4; and finally cow 3 and cow 4.

解答

题意:有一组数组n,要求这n个数两两组合能拼凑出多少对和(ai+aj)小于或等于M的组合。

思路:先排序,然后直接暴力。
Accepted Code:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 20005;
typedef long long ll;
int p[MAXN];
int main() {
    int n, m, ans = 0;
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++)
        scanf("%d", &p[i]);
    sort(p, p + n);
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (p[i] + p[j] <= m)
                ans++;
            else break;
        }
    }
    printf("%d\n", ans);
    return 0;
}


来源:子夜葵
全部评论

相关推荐

02-14 15:34
门头沟学院 Java
Java抽象带篮子:专业技能怎么写可以看看我发的帖子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务