zoukankan      html  css  js  c++  java
  • poj 1218 TheDrunk Jailer(醉汉看守)

    THE DRUNK JAILER(本题有规律可循)
    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 19918   Accepted: 12582

    Description

    A certain prison contains a long hall of n cells, each right next to each other. Each cell has a prisoner in it, and each cell is locked. One night, the jailer gets bored and decides to play a game. For round 1 of the game, he takes a drink of whiskey,and then runs down the hall unlocking each cell. For round 2, he takes a drink of whiskey, and then runs down the hall locking every other cell (cells 2, 4, 6, ?). For round 3, he takes a drink of whiskey, and then runs down the hall. He visits every third cell (cells 3, 6, 9, ?). If the cell is locked, he unlocks it; if it is unlocked, he locks it. He repeats this for n rounds, takes a final drink, and passes out. Some number of prisoners, possibly zero, realizes that their cells are unlocked and the jailer is incapacitated. They immediately escape.
    Given the number of cells, determine how many prisoners escape jail.

    Input

    The first line of input contains a single positive integer. This is the number of lines that follow. Each of the following lines contains a single integer between 5 and 100, inclusive, which is the number of cells n.

    Output

    For each line, you must print out the number of prisoners that escape when the prison has n cells.

    Sample Input

    2
    5
    100

    Sample Output

    2
    10
    初看题目,觉得得用两重for循环,并设一个标记数组,来表示牢房是开或者是关;于是写了下面的代码
    #include<stdio.h>
    #include<string.h>
    int main()
    {   int a[110];
        int i,j,n,m,count;
        scanf("%d",&n);
        while(n--)
        {    scanf("%d",&m);
             count=0;
             memset(a,0,sizeof(a));//sizeof()括号中要写成数组名,而不能是数组中的某个元素!!
             for(i=1;i<=m;i++)
                 for(j=i;j<=m;j+=i)//减少了循环的次数
                     a[j]=!a[j];//也可改写成a[j]=1-a[j]
             for(i=1;i<=m;i++)
                if(a[i])
                    count++;
             printf("%d\n",count);
        }
             return 0;
    }

    后来观察输出的结果,发现有规律可循:随着输入的值增加,答案的值也在增加,并且恰好是输入值等于平方数的时候答案增1.
    输入                    输出

    1~3         1

    4~8       2

    9~15                  3

    16~24      4

    25~35      5

    ……

    #include<stdio.h> 
    #include<math.h>                      
    int main()
    {   
        int n,m;
        scanf("%d",&n);
        while(n--)
        {    scanf("%d",&m);
             printf("%d\n",sqrt(m));
        }
        return 0;
    }
       
  • 相关阅读:
    分布式中各种概念汇总
    JMS
    spring boot jpa mysql
    spring boot 视图层(JAVA之学习-2)
    idea+spring boot的初学(JAVA学习之1)
    Yii在cli模式下执行一些脚本的配置
    在centos下安装django
    python简单的发送邮件
    ElasticSearch-PHP的API使用(二)
    Elasticsearch的PHP的API使用(一)
  • 原文地址:https://www.cnblogs.com/fengyuzhongdexiongying/p/TheDrunkJailer.html
Copyright © 2011-2022 走看看