贪心算法:排列算式

题目描述

给出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;
} 
相关推荐
谢景行^顾21 分钟前
数据结构知识掌握
linux·数据结构·算法
ShineWinsu1 小时前
对于数据结构:堆的超详细保姆级解析——下(堆排序以及TOP-K问题)
c语言·数据结构·c++·算法·面试·二叉树·
DuHz1 小时前
基于时频域霍夫变换的汽车雷达互干扰抑制——论文阅读
论文阅读·算法·汽车·毫米波雷达
_OP_CHEN2 小时前
C++进阶:(五)map系列容器的全面解析
开发语言·c++·map·红黑树·stl容器·键值对·mapoj题
hetao17338372 小时前
ZYZ28-NOIP模拟赛-Round4 hetao1733837的record
c++·算法
大米粥哥哥2 小时前
c++ libcurl报错Send failed since rewinding of the data stream failed【已解决】
开发语言·c++·http·curl·rewind
Nebula_g2 小时前
C语言应用实例:解方程(二分查找)
c语言·开发语言·学习·算法·二分查找·基础
woshimyc2 小时前
ESP32连接ThingsCloud上传设备数据(智慧小灯)
c++·物联网
Maple_land2 小时前
Linux复习:系统调用与fork
linux·运维·服务器·c++·centos
墨雪不会编程2 小时前
C++的基础语法篇一 ——命名空间
开发语言·c++