zoukankan      html  css  js  c++  java
  • 算法练习——聪明的情侣

    一、聪明的情侣

      酋长的女儿艾丽要出嫁了,按以往的风俗习惯,要搭个高台,台下是众多的求婚者,艾丽在台上扔束花,扔在台下谁身上,艾丽就得嫁给谁。
    但她担心落不到心爱的雷蒙身上。艾丽私下约雷蒙商量如何是好。雷蒙想出了一个主意……艾丽便和父亲说:“我不愿意搭台撒花,这么多人来
    ,挤在一起乱哄哄的,没秩序。”父亲说,“不这样也可以,但结婚时要当场在人群中决定嫁给谁,不许指名,方法你自己定。”艾丽高兴的告
    诉主持人如何行事。婚日来临,人群拥挤,主持人叫求婚者排成一队,雷蒙在队外数了数队列共有101人,于是自己找了个合适的位置也站在队列
    中,主持人要大家从前往后1,2,1,2……报数,报单数的退出场外,余下的人位置不变,再重新从前往后1,2,1,2……报数,报单数的退场,
    如此下去最后只剩一人,艾丽便嫁给谁。大家惊奇的发现最后剩下的竟是雷蒙。请用程序回答雷蒙刚开始站在队列中的第几个位置。

    思路一:
       转换成链表,每次去除单数。最后剩下唯一的数,结束。
    思路二:
       转换为数学问题。求人数中2的阶乘最大数。 64 属于数学口算。

    #include "stdafx.h"
    #include <stdio.h>
    #include <iostream>
    #define NULL 0
    
    struct People {
        int index;
        struct People* next;
    };
    
    struct People* head;
    struct People* hail;
    
    void init(int num){
        struct People *p;
        head = (struct People*)malloc(sizeof(struct People));
        hail = (struct People*)malloc(sizeof(struct People));
        hail ->index = -1;
        hail ->next = NULL;
        head ->index = 0;
        head->next = hail;
        for(int i = num;i>0;i--){
            p = (struct People*)malloc(sizeof(struct People));
            p->index = i;
            p->next = head->next;
            head->next = p;        
        }
    }
    void remove(struct People *people){
        struct People * p;
        p = people->next;
        people ->next = p->next;
        //printf("remove : %d
    ",p->index);
        free(p);
    }
    int search(){
        struct People *p;
        int num = 102;
        while(head->next->next->index>0){
            p = head;
            while(p->index>=0&&p->next->index>0){
                remove(p);
                num--;
                p=p->next;
            }
            //printf("remain: %d
    ",num);
        }
        return head->next->index;
    }
    
    void freeALL(){
        struct People *p;
        while(head->next->index>0){
            p = head->next;
            head->next = p->next;
            free(p);
        }
        free(head);
        free(hail);
    }
    
    /**
    第二种解题思路: 
    直接转换为数学问题,就是求 num中2的阶乘最大的
    double fun(int n)
    {
        return Math.Pow(2, Math.Floor(Math.Log(n, 2)));
    }
    */
    
    int main()
    {
        int last;
        init(102);
        last = search();
        printf("最后一个数字是:%d",last);
        freeALL();
        getchar();
        return 0;
    }
  • 相关阅读:
    Ubuntu 指令汇总
    ROS环境下Pointgrey相机的配置方法
    BUG战斗史 —— 日期格式与字符串之间的转换
    Effective Java —— 使类和成员的可访问性最小化
    JDBC和桥接模式
    Effective Java —— 覆盖equals时总要覆盖hashCode
    AutoValue —— Generated immutable value classes
    Effective Java —— 覆盖equals时遵守通用约定
    Effective Java —— try-with-resources 优先于 try-finally
    Effective Java —— 消除过期的对象引用
  • 原文地址:https://www.cnblogs.com/zhuqingqin/p/5392265.html
Copyright © 2011-2022 走看看