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

题目:https://vjudge.net/problem/UVA-12108

思路:据题意模拟过程,只要读明白题并且考虑清楚每个时刻切换时所有学生的状态是一起变化的就问题不大。

代码:c语言

#include <stdio.h>
typedef struct
{
    int a;//清醒时长
    int b;//睡眠时长
    int c;//当前时间
    int condition;//1睡眠,0清醒
} Student;
//判断是否所有人都清醒
int all_awaken(Student s[], int n)
{
    int i;
    for(i=0; i<n; i++)
    {
        if(s[i].condition!=0)
            return 0;
    }
    return 1;
}
//判断该时间是否睡的人严格大于醒的人
int check(Student s[], int n)
{
    int i,sl=0,aw=0;
    for(i=0; i<n; i++)
    {
        if(s[i].condition==1)
        {
            sl++;
        }
        else
        {
            aw++;
        }
    }
    if(sl>aw)
        return 1;
    else
        return 0;
}
int main()
{
    Student s[20];
    int n,cases=0,t,time,f;
    int i;
    while(scanf("%d", &n)!=EOF)
    {
        if(n==0)
            break;
        cases++;
        for(i=0; i<n; i++)
        {
            scanf("%d%d%d", &s[i].a, &s[i].b, &s[i].c);
            s[i].condition = s[i].c>s[i].a?1:0;
        }
        t = all_awaken(s, n);
        time = 1;
        if(t==0)
        {
            for(time=2; time<1000; time++)
            {
                f = check(s, n);
                for(i=0; i<n; i++)
                {
                    if(++s[i].c==s[i].a+1)
                    {
                        if(f==1)
                        {
                            s[i].condition = 1;
                        }
                        else
                        {
                            s[i].c -= s[i].a;
                        }
                    }
                    else if(s[i].c==s[i].a+s[i].b+1)
                    {
                        s[i].condition = 0;
                        s[i].c = 1;
                    }
                }
                if(all_awaken(s, n))
                {
                    t = 1;
                    break;
                }
            }
        }
        if(t)
        {
            printf("Case %d: %d\n", cases, time);
        }
        else
        {
            printf("Case %d: -1\n", cases);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值