其他分享
首页 > 其他分享> > 选数(代码源每日一题)

选数(代码源每日一题)

作者:互联网

选数(代码源每日一题)

选数 - 题目 - Daimayuan Online Judge

抽屉原理

  1. 求出前缀和 mod n 后的值,若前缀和的某一项 i 为 0,则 [1, n] 就是满足条件的区间
  2. 若前缀和没有为 0 的项,由于有 \(s_1-s_n\), n 个数,值域分布在 \([1,n-1]\) 中,所以一定存在 \(s_l=s_r\), \([l+1,r]\) 就是满足条件的区间
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
using namespace std;
#define endl "\n"

typedef long long ll;
typedef pair<int, int> PII;

const int N = 1e5 + 10;

int a[N], s[N];
int n;
int mp[N];
int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];
		s[i] = (s[i-1] + a[i]) % n;
	}
	for (int i = 1; i <= n; i++)
	{
		if (s[i] == 0)
		{
			cout << i << endl;
			for (int j = 1; j <= i; j++)
				cout << j << " ";
			cout << endl;
			return 0;
		}
	}
	for (int i = 1; i <= n; i++)
	{
		if (mp[s[i]] == 0)
			mp[s[i]] = i;
		else
		{
			cout << i - mp[s[i]] << endl;
			for (int j = mp[s[i]] + 1; j <= i; j++)
				cout << j << " ";
			cout << endl;
			return 0;
		}
	}
    return 0;
}

标签:前缀,int,选数,代码,long,tie,include,每日
来源: https://www.cnblogs.com/hzy717zsy/p/16370818.html