贪心算法:排列算式

题目描述

给出n数字,对于这些数字是否存在一种计算顺序,使得计算过程中数字不会超过3也不会小于0?

输入描述:

复制代码
首行给出一个正整数t,(1≤t≤1000)代表测试数据组数

每组测试数据第一行一个正整数n,(1≤n≤500)

第二行包含n个以空格分隔的数字

输入保证每一个数字都是 −3, −2, −1, +0, +1, +2, +3 的其中一个。

输出描述:

复制代码
每组测试数据输出一行,“Yes” or “No”

输入

复制代码
2
4
+3 +2 -1 -2
5
+3 +2 +1 +0 +2

输出

复制代码
Yes
No

说明

复制代码
第一组依照 +3,−2,+2,−1 的顺序由左至右计算总和,过程会依序算得 3, 1, 3, 2,满足题目要求

很显然第二组不存在满足要求的计算顺序
cpp 复制代码
#include <bits/stdc++.h>
#include<iostream>
using namespace std;
    int N, n, a[7], *cnt; 
    bool check() {
	int t = 0;
	for (int i = -3; i <= 3; i++) {
		t += i * cnt[i];
	}
	if (t > 3 || t < 0) 
        return false;
    t = min(cnt[-3], cnt[3]);
	cnt[-3] -= t;
	cnt[3] -= t;
	t = min(cnt[2], cnt[-1]);
	cnt[2] -= t;
	cnt[-1] -= t;
	cnt[1] += t;
	t = min(cnt[-3], cnt[1]);
	cnt[-3] -= t;
	cnt[1] -= t;
	cnt[-2] += t;
	if (cnt[-3] > 0) 
        return false;
	t = min(cnt[-2], cnt[1]);
	cnt[-2] -= t;
	cnt[1] -= t;
	cnt[-1] += t;
	t = min(cnt[3], cnt[-1]);
	cnt[3] -= t;
	cnt[-1] -= t;
	cnt[2] += t;	
	if (cnt[3] > 1) 
        return false;
	return true;
}
int main() {
	cin>>N;
	cnt = &a[3];
	while (N--) {
		memset(a, 0, sizeof(a));
		cin>>n;
		int t;
		for (int i = 1; i <= n; i++) {
			cin>>t;
			cnt[t]++;
		}
		if (check()) {
			cout<<"Yes\n";
		} else {
			cout<<"No\n";
		}
	}
	return 0;
} 
相关推荐
沐怡旸2 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥2 小时前
C++ 内存管理
c++
聚客AI2 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v5 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工7 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农8 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了9 小时前
AcWing学习——双指针算法
c++·算法
感哥9 小时前
C++ 指针和引用
c++
moonlifesudo9 小时前
322:零钱兑换(三种方法)
算法
感哥19 小时前
C++ 多态
c++