题解 | Cows Of The-牛客假日团队赛5C题

C-Cows Of The Round Table_牛客假日团队赛5

https://ac.nowcoder.com/acm/contest/984/C

题目描述

Farmer John is calling his N (1 <= N <= 10) cows to a very important meeting at a round table.
The cows are rather anxious about this meeting since they want to put forth their very best image. To make the table arrangement attractive, they want to ensure that any two cows sitting next to each other to differ in height by no more than K (1 <= K <= 1,000,000) millimeters (cow i has integer height Hi (1 <= Hi <= 1,000,000) millimeters).
Help calculate the number of ways the cows can sit down at the round table such that no two adjacent cows differ in height by more than K millimeters. Two ways are different if there is at least one cow with a different cow to its left in each arrangement.
The answer is guaranteed to fit in a 32-bit signed integer.

输入描述:

Line 1: Two space-separated integers, N and K
Lines 2..N+1: Line i+1 contains height Hi

输出描述:

Line 1: The number of ways that the cows can sit down at the round table such that two adjacent cows do not differ in height by more than K millimeters.

示例1

输入
4 10
2
16
6
10
输出
2
说明
There are 4 cows, with heights 2, 16, 6, and 10. Two cows whose heights differ by more than 10 do not want to sit next to each other.
Clearly the cows with heights 2 and 16 must be opposite each other, so there are 2 ways to place the cows of height 6 and 10.

解答

题目大意 : 输入牛的数量和限制高度,输出有多少种坐法(所有牛围成一圈)可以让相邻两头牛的高度不超过K
思路 : 由于数据比较小,可以全排列所有的情况,然后依次判断即可,注意全排列排的是下标
AC代码 :
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 10 + 5;
 
int p[MAXN], s[MAXN], n, k, ans;
 
int main()
{
    cin >> n >> k;
    for (int i = 1; i <= n; i++) cin >> p[i];
    sort (p + 1, p + n + 1);   // 先排序
    for (int i = 1; i <= n; i++) s[i] = i;
    do {
        bool flag = 1;
        if (abs (p[s[1]] - p[s[n]]) > k) flag = 0;  // 首尾判断
        else {
            for (int i = 2; i <= n; i++) {
                if (abs (p[s[i]] - p[s[i - 1]]) > k) {
                    flag = 0;
                    break;
                }
            }
        }
        if (flag) ans++;
    }
    while (next_permutation (s + 1, s + n + 1));
    cout << ans / n << endl;   // 每种情况都有n - 1个重复的,所以要除以n
    return 0;
}

来源:东野圭吾#
全部评论

相关推荐

07-11 10:56
门头沟学院 Java
码客明:大胆的说自己能实习6个月就行
点赞 评论 收藏
分享
06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
程序员小白条:主要没亮点,项目也是网上的,平平无奇,那只能海投了,奖项总得有一些,然后就是现在最好是前后端都会,自己能做项目并且运维的,要么找星球项目改改,要么找个开源项目改改,自己能拓展功能才是主要的,跟做效率很低很低
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务