贪心算法:排列算式

题目描述

给出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;
} 
相关推荐
eggwyw9 小时前
C++ union 的一种妙用法
开发语言·c++
罗西的思考9 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
ShineWinsu11 小时前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步12 小时前
string的实现(1)
c++·笔记·visual studio
kyle~14 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
敲上瘾14 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
牢姐与蒯15 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好16 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
lcj251116 小时前
[C++] C++11
开发语言·c++·笔记
电科_银尘17 小时前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归