2022牛客寒假算法基础集训营1(补题:A、F、H)

目录

A 九小时九个人九扇门 

F 中位数切分

H 牛牛看云



A 九小时九个人九扇门 

 
示例1

输入

9
1 2 3 4 5 6 7 8 9

输出

56 56 58 56 56 58 56 56 59

背包问题

f[i][j]表示从前i个人中搭配出开j扇门的方法总数

若是第i个人未被选中,那么有 

f[i][j] = f[i][j]+f[i-1][j];

 若是第i个人被选中,那么有

f[i][(x+j)%9] = f[i][(x+j)%9] + f[i-1][j];

#include<iostream>
using namespace std;

const int MOD = 998244353;
const int N = 1e5+10;
int v[N], f[N][10];

int main()
{
	int n;
	cin >> n;
	
	int x;
	f[0][0] = 1;
	for(int i = 1; i <= n; i ++)
	{
		scanf("%d", &x);
		for(int j = 0; j < 9; j ++)
		{
			f[i][j] = ( f[i][j] + f[i-1][j])%MOD;
			f[i][(x+j)%9] = ( f[i][(x+j)%9] + f[i-1][j])%MOD;
		}
	}
	for(int i = 1; i <= 8; i ++) cout << f[n][i] << " ";
	cout << f[n][0]-1 ;
	return 0;
}

F 中位数切分

示例1

输入

4
5 4
10 3 2 3 2
5 3
5 2 3 3 2
2 5
4 5
5 2
10 3 2 3 2

输出

-1
1
-1
5

逆向思考一下,若是截取到的每段都满足中位数大于等于m

那么就算把他们合在一块,最终的中位数也满足大于等于m

#include<iostream>
using namespace std;

int main()
{
    int t;
    cin >> t;
    
    int n, m;
    while(t --)
    {
        cin >> n >> m;
        
        int x, cnt1 = 0, cnt2 = 0;
        for(int i = 0; i < n; i ++){
            scanf("%d", &x);
            if(x < m) cnt1 ++;
            else cnt2 ++;
        }
        
        if(cnt2 <= cnt1) puts("-1");
        else cout << cnt2-cnt1 << endl;
    }
    return 0;
}

H 牛牛看云

示例1

输入

4
500 501 500 499

输出

8

哈希+组合数学

这道题暴力很好想, 但卡在了优化上

暴力法, 这里我把

看作ai-500 与 aj-500的和的绝对值

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

const int N = 1010;
int a[N];
int m[N][N];
int main()
{
    int n; 
    cin >> n;
    
    long long res = 0;
    int x;
    for(int i = 0; i < n; i ++) {
        scanf("%d", &x);
        a[i] = x-500;
    }
    for(int i = 0; i < n; i ++)
        for(int j = i; j < n; j ++){
            res += abs(a[i]+a[j]);
        }
    cout <<res;
    return 0;
}

那么该如何优化呢,  我们可以发现我们需要求的是矩阵(因此与输入样例中的数字顺序无关)上对角的一个三角形内所有元素绝对值之和,见下图

 因此我们可以求矩阵上所有数的和多加上对角线上的数之和, 最后再除以二

因此可以通过利用哈希合并重复数的方法减少计算量(如样例中的两个五百)

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

typedef long long LL;
const int N = 1010;
int cnt[N];
int m[N][N];
int main()
{
    int n; 
    cin >> n;
    
    LL res = 0;
    int x;
    for(int i = 0; i < n; i ++) {
        scanf("%d", &x);
        cnt[x] ++;
        res += abs(2*x - 1000);
    }
    
    for(int i = 0; i <= 1000; i ++)
        for(int j = 0; j <= 1000; j ++)
            res += (LL)cnt[i]*cnt[j]*abs(i+j-1000);
    cout <<res/2;
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泥烟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值