Find a multiple

来源:互联网 发布:天猫mac pc客户端下载 编辑:程序博客网 时间:2024/06/05 17:33
链接:http://acm.hust.edu.cn/vjudge/problem/17962/origin

题目:The input contains N natural (i.e. positive integer) numbers ( N <= 10000 ). Each of that numbers is not greater than 15000. This numbers are not necessarily different (so it may happen that two or more of them will be equal). Your task is to choose a few of given numbers ( 1 <= few <= N ) so that the sum of chosen numbers is multiple for N (i.e. N * k = (sum of chosen numbers) for some natural number k).

题意:给一串共n数字,求一个连续的字串使子串的和为n的倍数。

分析:利用优化的前缀和,优化的方法是前缀和数组都对n取余。这样如果存在前缀和为零或者前缀和相同就找到了字串。

题解:
#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <queue>#include <stack>#include <vector>#include <map>#include <string>#include <cstring>#include <functional>#include <cmath>#include <cctype>#include <cfloat>#include <climits>#include <complex>#include <deque>#include <list>#include <set>#include <utility>#define rt return#define fr freopen("in.txt","r",stdin)#define fw freopen("out.txt","w",stdout)#define ll long long#define ull unsigned long long#define detie ios_base::sync_with_stdio(false);cin.tie(false);cout.tie(false)#define pii pair<int,int>#define lowbit(x) x&(-x)using namespace std;#define maxi 0x3f3f3f3f#define MAX 100010int s[10010];int sum[10010];int rest[10010];int main(){//fr;detie;int n;cin >> n;for (int i = 1; i <= n; i++){cin >> s[i];sum[i] = (sum[i - 1] + s[i]) % n;}for (int i = 1; i <= n; i++){if (sum[i] == 0){cout << i << endl;for (int j = 1; j <= i; j++)cout << s[j] << endl;break;}else if (rest[sum[i]] == 0)rest[sum[i]] = i;else{cout << i - rest[sum[i]] << endl;for (int j = rest[sum[i]] + 1; j <= i; j++)cout << s[j] << endl;break;}}rt 0;}

0 0
原创粉丝点击