17暑假多校联赛7.11 HDU 6130 Kolakoski

来源:互联网 发布:室内设计上海知乎 编辑:程序博客网 时间:2024/06/05 19:38

Kolakoski

Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 524288/524288 K (Java/Others)

Problem Description

This is Kolakosiki sequence: 1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,2,1……. This sequence consists of 1 and 2, and its first term equals 1. Besides, if you see adjacent and equal terms as one group, you will get 1,22,11,2,1,22,1,22,11,2,11,22,1……. Count number of terms in every group, you will get the sequence itself. Now, the sequence can be uniquely determined. Please tell HazelFan its nth element.

Input

The first line contains a positive integer T(1≤T≤5), denoting the number of test cases.
For each test case:
A single line contains a positive integer n(1≤n≤107).

Output

For each test case:
A single line contains a nonnegative integer, denoting the answer.

Sample Input

212

Sample Output

12


题目网址:http://acm.hdu.edu.cn/showproblem.php?pid=6130

分析

题意:给定Kolakoski序列a,求第n位是1还是2
Kolakoski序列是仅仅由1和2组成的一个无限的序列,它的前几项为1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,2,1,2,1,1,2,1,2,2,1,1,……通过将相同的数字分为一组,原序列a的第i位表示第i组有几个元素,a是Kolakoski序列,b表示第i组的元素个数,根据下图来看
这里写图片描述
b[2]=a[2]=2,所以第二组有两个元素,第二组只有一个2,所以a[3]=2,所以b[3]=a[3]=2,所以第三组是两个元素,因为上一组是2,所以第三组是1,所以a[4],a[5]都是1,也可以发现第奇数组的元素是1,第偶数组的元素是2,所以根据这个规律直接打表
我的代码中的b数组用来存放前i组的元素个数,以此来判断n在哪一组,又因为第奇数组的元素是1,第偶数组的元素是2,所以可以直接判断第n项是1还是2

代码

#include<bits/stdc++.h>using namespace std;const int MAX=1e7+50;int a[MAX],b[MAX];void Kols(){    int flag=1;    for(int i=1; i<=MAX; i++)    {        b[i]=b[i-1]+a[i];        for(int j=1; j<=a[i]; j++)        {            a[flag]=(i&1);///判断第i组的下标i是奇数还是偶数,来给a中元素赋值            if(a[flag]==0)a[flag]=2;            flag++;            if(flag>(MAX-40))return;///如果数值已经存够MAX位就不用继续循环了        }    }}int main(){    int T;    scanf("%d",&T);    a[0]=0;    a[1]=1;    a[2]=2;    memset(b,0,sizeof(b));    Kols();    while(T--)    {        int n,ans=0,i;        scanf("%d",&n);        for(i=1; i<MAX; i++)        {            if(b[i]>=n)///如果b[i]的值大于等于n,则说明n在第i组            {                ans=i;                break;            }        }        if(!(ans&1))printf("2\n");///根据i的奇偶来输出答案        else printf("1\n");    }}
原创粉丝点击