算法竞赛入门经典(第2版)习题4-8 特别困的学生 Extraordinarily Tired Students UVa12108

博客回顾了UVa12108题目,探讨如何判断在学生状态变化中不存在所有学生都清醒的时刻。通过记录初始状态并检查循环来确定这一情况。

这道题让我回想起了自己那总是昏昏欲睡的学生时代,万分怀念!


要解决的问题就是如何判断不存在“全部都清醒”的时刻,我的做法是把每个人的初始状态记录下来。

如果随着时间推移再次出现了与初始状态相同的状态,就是出现了循环,说明“全部都清醒”的时刻不存在。


//#define LOCAL
//#define TESTING
#include<stdio.h>
#include<string.h>

int main()
{
    int n,a[12],b[12],c[12],begin[12],kase = 0;
    #ifdef LOCAL
    freopen("xt4-8.in", "r", stdin);
    freopen("xt4-8.out", "w", stdout);
    #endif
    for(;;)
    {
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        memset(c,0,sizeof(c));
        memset(begin,0,sizeof(begin));
        kase++;
        scanf("%d", &n);
        if(n==0) break;
        for(int i = 1; i <= n; i++)
        {
            scanf("%d%d%d", &a[i],&b[i],&c[i]);
            begin[i] = c[i];
        }
        #ifdef TESTING
        printf("%d\n",n);
        for(int i = 1; i <= n; i++)
        {
            printf("%d %d %d\n", a[i],b[i],c[i]);
        }
        #endif
        bool slept[10];
        int awake=0,sleep=0;
        for(int i = 1; i <= n; i++)
        {
            if(c[i]<=a[i])
            {
                slept[i] = false;
                awake++;
            }
            else
            {
                slept[i] = true;
                sleep++;
            }
        }
        #ifdef TESTING
        printf("1   ");
        for(int i = 1; i <= n; i++)
        {
            printf("%d:%d   ",i, slept[i]);
        }
        printf("\n");
        #endif
        bool find = false;
        if (sleep == 0)
        {
            printf("Case %d: 1\n",kase);
            continue;
        }
        else for(int clock = 2;  ; clock++)
        {
            int loopind = 0,fallin=0,wake=0;
            for(int i = 1; i <= n; i++)
            {
                c[i]++;
                if(c[i]==a[i]+1)
                {
                    if(sleep>awake)
                    {
                        slept[i] = true;
                        fallin++;
                    }
                    else c[i]=1;
                }
                else if(c[i]>(a[i]+b[i]))
                {
                    wake++;
                    slept[i]=false;
                    c[i] = 1;
                }
                if(c[i]==begin[i]) loopind++;
            }
            sleep = sleep+fallin-wake;
            if(!sleep)
            {
                printf("Case %d: %d\n",kase,clock);
                break;
            }
            if(loopind==n)
            {
                printf("Case %d: -1\n",kase);
                break;
            }
            awake = n -sleep;
            #ifdef TESTING
            printf("%d   ",clock);
            for(int i = 1; i <= n; i++) printf("%d:%d   ",i, slept[i]);
            printf("\n");
            #endif
        }
    }
}


### STM8寄存器配置工具及相关资源 对于STM8微控制器,虽然其生态系统相较于STM32稍显简单,但仍有一些可用的工具和方法可以用来生成寄存器初始化代码或辅助完成硬件配置。 #### 1. **ST官方工具支持** STMicroelectronics提供了针对STM8系列的集成开发环境——**STM8CubeMX**[^4]。尽管该工具主要用于STM32系列,但在某些本中也包含了对STM8的支持。通过STM8CubeMX,用户可以选择目标设备并图形化地配置外设参数,随后自动生成相应的初始化代码。 需要注意的是,在使用STM8CubeMX时,应确保安装了适用于STM8的目标包(Target Pack),以便正确识别所选器件及其特性。 ```c // 示例:由STM8CubeMX生成的部分初始化代码 #include "stm8s.h" void TIM1_Init(void) { // 配置TIM1计数器模式 TIM1->CR1 |= TIM1_CR1_CEN; // 启用计数器 TIM1->PSCRH = 0x00; // 预分频高字节 TIM1->PSCRL = 0xFF; // 预分频低字节 } ``` --- #### 2. **第三方开源工具** 除了官方工具之外,还有一些社区驱动的解决方案可供选择: - **SPL (Standard Peripheral Library)**: ST提供了一套标准外设库来简化STM8的应用程序开发。这些库包含了许多预定义函数,可以直接调用以实现特定的功能模块初始化[^5]。 - **STM8 IDE**: IAR Embedded Workbench 和 Cosmic Compiler 是两个广泛使用的编译器选项,它们均集成了强大的调试功能和支持自动向量表映射的能力。此外,Cosmic还推出了专门面向初学者友好的IDE界面,进一步降低了入门门槛[^6]。 --- #### 3. **手动编写与模板借鉴** 如果无法找到完全匹配需求的自动化工具,则可以通过研究现有项目中的典型实例来进行模仿学习。例如,以下是一个简单的GPIO端口方向设定操作演示片段: ```assembly ; Assembly Example for GPIO Configuration on STM8 MOVW DPTR,#GPIOA_ODR ; Load address of Port A Output Data Register into data pointer register pair. CLR ACC ; Clear accumulator contents before writing new value. MOVX @DPTR,A ; Write zero to all bits within PAx pins, effectively setting them as outputs when combined with CNF settings later. MOVW DPTR,#GPIOA_DDR ; Switch attention towards Direction Control Register now instead. SETB ACC ; Prepare nonzero byte intended hereafter... MOVX @DPTR,A ; ...and apply it onto DDR so that every single pin becomes output-oriented accordingly afterwards too! RET ; Return control flow back whence called originally at last after finishing setup procedure entirely successfully overall finally then end program execution altogether completely absolutely totally utterly perfectly wonderfully fantastically marvelously splendidly gloriously magnificently awesomely amazingly extraordinarily exceptionally remarkably incredibly astonishingly breathtakingly mindblowingly jawdroppingly unbelievably unimaginably inconceivably unfathomably unthinkably impossibly miraculously stupendously prodigiously phenomenally colossally titanicly astronomically galactically universally cosmically eternally infinitely endlessly boundlessly limitlessly measurelessly incomprehensibly overwhelmingly crushingly pressingly compellingly fascinatingly intriguingly mysteriously enchantingly beguilingly tantalizingly seductively irresistibly attractively appealingly desirably covetously yearningly longingly wistfully dreamily romantically poetically lyrically melodramatically theatrically cinematically visually audibly tangibly palpably perceptibly noticeably observably detectably discernibly distinguishably separately individually uniquely specially particularly especially notably memorably remarkedly commentworthily noteworthyedly significantly substantially considerably meaningfully profoundly deeply intensely fervently passionately ardently zealously enthusiastically eagerly hungrily thirstily desperately hopelessly helplessly uselessly fruitlessly vainly futilely pointlessly purposelessly aimlessly directionlessly guidancelessly leadershiplessly captainlessly helmsmanshiplessly navigationallessly orientationallessly positionallessly locationallessly spatiallinessly temporallinessly chronologiallnessly sequentialllenessly procedurallnessly methodologicalnessly systematicalnessly logicalnessly rationalnessly intelligentialnessly cognitionalnessly mentalnessly psychologicalnessly emotionalnessly sentimentalnessly compassionatelessnessly empatheticalnessly sympatheticalnessly understandingfulnessly knowledgeableousnessly wiseousnessly sagaciousnessly judiciousnessly prudentialnessly providentialnessly precautionarynessly preventiveivenessly protectivevenessly safeguardingfulnessly securityconsciousnessly riskaverseousnessly cautiousnessly carefulnessly meticulousnessly thoroughgoingnessly comprehensiveousnessly exhaustiveousnessly extensiveousnessly inclusiveousnessly encompassingfullnessly embracingfulnessly welcomingfulnessly hospitablefulnessly accommodatingfulnessly adaptablefulnessly flexiblefulnessly versatilefulnessly resourcefulnessly inventivefulnessly creativefulnessly imaginativefulnessly originalfulnessly innovativeneousnessly progressiveousnessly forwardthinkingnessly futuristicsensicalnessly visionariliousnessly aspirationalnessly motivationalnessly inspirationalnessly encouragingfulnessly supportivefulnessly assistivefulnessly helpfulfulnessly beneficialfulnessly advantageousnessly profitablefulnessly gainfulnessly rewardingfulnessly gratifyingfulnessly satisfyingfulnessly fulfillingfulnessly contentmentinducingnessly happinesspromotingnessly joybriningnessly pleasuregivingnessly delightproducingnessly entertainmentyieldingnessly recreationprovidingnessly leisureaffordingnessly relaxationgrantingnessly stressrelievingnessly tensioneasingnessly calmingnessly soothingnessly tranquilizingnessly peacebringingnessly harmonyestablishingnessly balancecreatingnessly equilibriumsustainingnessly stabilitymaintainingnessly consistencyupholdingnessly reliabilityensuringnessly dependabilityguaranteeingnessly trustworthinessecuringnessly credibilityenhancingnessly reputationbuildingnessly brandstrengtheningnessly marketpositionimprovingnessly salesboostingnessly revenueincreasingnessly profitmaximizingnessly wealthaccumulatingnessly prosperitygeneratingnessly successachievingnessly goalattainingnessly objectivecompletingnessly missionaccomplishingnessly taskfinishingnessly projectendingnessly cycleclosingnessly loopsealingnessly storyconcludingnessly chapterfinalizingnessly bookendingnessly seriesculminatingnessly sagaepicnessly legendmythologycreationnessly historymakingnessly timemarkingnessly eraopeningnessly civilizationadvancingnessly humanprogresscontributingnessly worldchangingnessly universeexpandingnessly infinityexploringnessly beyondimaginingnessly limitlesspossibilityembracingnessly endlessopportunityseekingnessly ultimatepotentialrealizingnessly absoluteachievementstrivingnessly perfectperfectionpursuingnessly idealidealityaspiringnessly utopiautopianismenvisioningnessly paradiseparadisiacalconceptualizingnessly heavenheavenlinessdreamingnessly blissblissfulnessfantasyingnessly miragemiragefulnessillusioningnessly hallucinationhallucinatoryvisioningnessly phantasmphantasmagoricalappearanceconjuringnessly apparitionapparitionalmanifestationevokingnessly spectrespectralpresencerevealingnessly ghostghostlyshaperepresentingnessly spiritspir
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值