zoukankan      html  css  js  c++  java
  • 左右相等

    Description

    Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?

    Input

    The first input line contains integer n (1 ≤ n ≤ 105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.

    Output

    Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.

    Sample Input

    Input
    9 
    1 5 -6 7 9 -16 0 -2 2
    Output
    3
    Input
    3 
    1 1 1
    Output
    0
    Input
    2 
    0 0
    Output
    1

    分析:
     直接用循环分成两半进行比较
     1 #include<iostream>
     2 using namespace std;
     3 #define maxn 100000+5
     4 int n, ans,flag;
     5 int sum,lsum, rsum;
     6 int arr[maxn];
     7 int judge(int m)
     8 {
     9     lsum = 0, rsum = 0;
    10     for (int i = 0; i <m; i++)
    11     {
    12         if (sum == 0)
    13         {
    14             if (i == m - 1)         //防止总和为零的时候再计算一次
    15                 break;
    16         }
    17             lsum += arr[i];           //左边的数的和
    18             rsum = sum - lsum;             //右边的数的和
    19             if (lsum == rsum)             //相等就加加
    20                 ans++;
    21     }
    22     if (ans)
    23     {
    24         flag = 1;
    25         return flag;
    26     }
    27     else
    28         return 0;
    29 }
    30 int main()
    31 {
    32      sum = 0,flag=0,ans=0;
    33     cin >> n;
    34     for (int i = 0; i < n; i++)
    35     {
    36         cin >> arr[i];
    37         sum += arr[i];
    38     }
    39     if (sum % 2 != 0)
    40         flag = 0;                  //总和为奇数,直接判断不可以分成相等的两半
    41     else
    42         judge(n);
    43     if (flag == 1)
    44         cout <<ans << endl;
    45     else
    46         cout << "0" << endl;
    47 
    48     return 0;
    49 }
     
  • 相关阅读:
    SpringBoot 官方文档中文版
    SpringBoot 官方文档中文版
    SpringBoot 官方文档中文版
    RK 打包脚本 make_ext4fs system.img
    Linux安装docker-compose
    Linux使用docker安装Jenkins 并进行jar包发布
    JAVA把InputStream 转 字节数组(byte[])
    SpringBoot简单整合分布式任务调度平台(XXL-JOB)
    SpringBoot项目bootstrap.yml配置文件不加载
    JAVA中Base64和byte数组(byte[]) 相互转换
  • 原文地址:https://www.cnblogs.com/Lynn0814/p/4711859.html
Copyright © 2011-2022 走看看