题目描述
Ranran has a sequence aaa of nnn integers a1,a2,⋯ ,ana_1, a_2, \cdots, a_na1,a2,⋯,an which satisfies ∑1ai≤12\displaystyle \sum \dfrac 1 {a_i} \leq \dfrac 1 2∑ai1≤21 and he is very proud of it, so he comes up with a problem for you.
You need to find out a sequence ccc of mmm integers c0,c1,⋯ ,cm−1c_0, c_1, \cdots, c_{m - 1}c0,c1,⋯,cm−1. With ccc, you construct an infinite sequence bbb, and bib_ibi equals to ci mod mc_{i\bmod m}cimodm. bbb must satisfy the condition that in every consecutive aia_iai numbers of bbb there exists a number equals to iii.
Please note that aaa is 1-indexed and b,cb, cb,c are 0-indexed. The value of mmm is decided by you.
Can you solve the problem?
输入描述:
The first line contains an integer n (1≤n≤105)n\ (1\leq n\leq 10 ^ 5)n (1≤n≤105). The second line contains nnn integers a1,a2,⋯ ,an (2≤ai≤2×105,∑1ai≤12)a_1, a_2, \cdots, a_n\ (2\leq a_i \leq 2 \times 10 ^ 5, \sum \dfrac 1 {a_i} \leq \dfrac 1 2)a1,a2,⋯,an (2≤ai≤2×105,∑ai1≤21).
输出描述:
The first line output an integer mmm.
The second line output mmm integers c0,c1,⋯ ,cm−1c_0, c_1, \cdots, c_{m - 1}c0,c1,⋯,cm−1.
You should guarantee that 1≤m≤1061\leq m\leq 10 ^ 61≤m≤106 and 1≤ci≤n1\leq c_i\leq n1≤ci≤n.
示例1
输入
1 2
输出
2 1 1
题意: 给出一个长度为n的数组a,已知ai的倒数之和小于等于0.5,需要构造出一个数组c,满足在c中每ai个元素都要出现i这个数字,c数组是一个无限循环的数组,输出循环节长度以及具体的循环节。
分析: 先分析一下题目中给出ai倒数和这个条件的用处,考虑ai倒数实际含义,其实就是平均每个位置出现ai多少次,那加和就是平均每个格子出现各种数字多少次,这个值大于1时肯定无解,小于等于1时肯定有解,而题目中给出的是小于等于1/2,所以可能是在暗示我们可以把ai值缩小,并且最多可以缩小1倍,这道题目其实不缩小ai也可以做,但是做法就会比较麻烦,而缩小ai具体是缩小到多少呢,不妨缩小到小于ai的最大的2的幂次,这样会有一个显然的好处,所有缩小后的ai都是2的幂次,这样只要循环节内部符合题意了,两循环节连接起来后仍然符合题意,不用考虑连接处是否会空出来很大的距离。
接下来就是具体构造了,显然可以对a进行排序,从小到大放入数字会更方便,初始化j = 1,然后枚举ai,为了简单起见待放入的值也用ai表示,如果cj为0那说明该位置可以放入ai,于是可以cj = ai, c(j+ai) = ai, ......, c(j+k*ai) = ai,否则将j++,持续这个过程直到遍历完a数组,由于一定有解所以每次j总能找到一个0位置,而且这个0的位置一定小于等于ai。
最后就是输出c数组就行了,不过ci为0的位置直接输出1,时间复杂度为O(n+m),m为小于max(ai)的最大的2的幂次。
具体代码如下:
#include <bits/stdc++.h>
#define pii pair<int, int>
using namespace std;
pii a[100005];
int res[200005];
signed main(){
int n;
cin >> n;
for(int i = 1; i <= n; i++){
scanf("%d", &a[i].first);
a[i].second = i;
int j = 0;
while((1<<j) < a[i].first) j++;
a[i].first = 1<<(j-1);
}
sort(a+1, a+n+1);
int m = a[n].first;
int j = 1;
for(int i = 1; i <= n; i++){
while(res[j]) j++;
for(int k = 0; j+k*a[i].first <= m; k++)
res[j+k*a[i].first] = a[i].second;
}
printf("%d\n", m);
for(int i = 1; i <= m; i++){
if(res[i]) printf("%d ", res[i]);
else printf("1 ");
}
return 0;
}