1. 程式人生 > 實用技巧 >D. Add to Neighbour and Remove

D. Add to Neighbour and Remove

分析:

讀題可知無論怎麼改變陣列,最後的和都不會邊,同時因為n較小,因此可以列舉最後剩下的陣列長度來解決。關於數字合併,因為列舉長度則可以知道最後的值,從左到右合併,如果出現合併的數字大於那後的值則不符合題意,如果出現一組合並的值能全部都等於最後的值這為答案,輸出合併資料即可。

#include <iostream>
#include <algorithm>
#include <string.h>
#include <map>
#include <math.h>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
const int maxn = 2 * 1e4 + 100;
const long long INF = 1e18;
 
 
int a[maxn];
int pre[maxn];
int main() {
	int t;
	scanf("%d", &t);
	while (t--) {
		int n;
		cin >> n;
		int sum = 0 ;
		for (int i = 1; i <= n; i++)
			cin >> a[i], sum += a[i], pre[i] = pre[i - 1] + a[i];
 
		for (int i = n; i >= 1; i--) {
			if (sum % i == 0) {
				int each = sum / i;
				int now = 0;
				int cnt = 0;
				int num = 0;
				for (int i = 1; i <= n; i++) {
					if (now != 0)
						num++;
					now += a[i];
					if (now == each) {
						now = 0 ;
						cnt++;
					} else if (now > each) {
						cnt = -1;
						break;
					}
				}
				if (cnt == i) {
					cout << num << endl;
					break;
				}
			}
		}
	}
 
}