【蓝桥备赛】小蓝和小桥的挑战——思维模拟

题目链接

小蓝和小桥的挑战

个人思想

题目要求所有数之积和所有数之和都不为 0 ,那么我们就在输入的数组的时候,记录下数组之和与数组中 0 的个数(这关系到数组之积是否为 0 )。

如果数组中存在 0, 那么首先需要将所有 0 变成 1 。之和,再去判断当前的和是否为 0,如果为0的话,只需要随意将一个正数 + 1即可(为什么是正数呢?如果一个数组和为0,而且不存在 0 的时候,那么必然有一个正数存在;而我们去修改一个负数,可能将该负数变为 0,违背题意)

参考代码

Java

为了避免因为Java自带Scanner读写比较慢的情况影响过题,以后都会使用自己封装的Scanner类

import java.io.*;

public class Main {
    static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner();
        int t = sc.nextInt();
        int n, a;
        while (t-- > 0) {
            n = sc.nextInt();
            int sum = 0, cnt = 0;
            for (int i = 1; i <= n; ++i) {
                a = sc.nextInt();
                sum += a;
                if(a == 0) {
                    cnt++;
                }
            }
            sum += cnt;
            if (sum == 0) ++cnt;
            out.println(cnt);
        }
        out.flush();
    }
}
class Scanner {
    static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    // 字符串快速读入对象
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public Scanner() {
    }
    public int nextInt() throws IOException {
        st.nextToken();
        return (int) st.nval;
    }
}

C/C++

#include<bits/stdc++.h>
using namespace std;

int n, a;

void solve()
{
    cin >> n;
    int sum = 0, cnt = 0;
    for (int i = 1; i <= n; ++i)
    {
        cin >> a;
        sum += a;
        if(a == 0) ++cnt;
    }
    sum += cnt;
    if(sum == 0) ++cnt;
    cout << cnt << '\n';
}

int main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int t;
    cin >> t;
    while(t--)
        solve();
}
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值