这个题自己没有做出来,看的luogu里面dalao们的题解,感触很深。实际上这个题,有贪心的思想,也有DP的思想。
当时看到这个题就想到了贪心,能闪烁就闪烁,但是没想明白在体力不够的时候该做什么。
看了题解之后,知道了如果遇见这种问题,可以同时开两个变量进行尝试,一个一直闪,没体力就恢复体力。另一个就一直走。
如果某一个时刻闪烁的距离大于了走的距离,那么就更新走的距离。这样,就是闪、恢复体力、走三者的最优搭配。
1 #include
2 #include
3 using namespacestd;4 intmain(){5 intenergy,dis,time;6 cin >> energy >> dis >>time;7 int s1,s2; s1 = s2 = 0;8 int temp =time;9 while(time > 0 and s1 = 10){12 energy-=10;13 s2+=60;14 }else energy+=4;15 s1 =max(s1,s2);16 time--;17 }18 if(s1 >= dis)cout<
如何验证贪心算法的正确性?
其实可以把闪烁的距离换一种理解方式: 闪烁的次数。因为闪烁次数固定了,闪烁的距离也就固定了。那么,s2变量实际上是在模拟当前时间内最大闪烁次数,而s1变量则是在模拟不闪烁、纯粹走路下当前时间内走的距离。如果在某一个时刻,发现s1 > s2了,说明在当前时间下,0次闪烁的行动距离小于若干次闪烁的行动距离。那么更新s1好了,让它等于s2。并继续模拟,s1还是不断的自增17,s2还是努力地试图再进行一次闪烁。
或许将s2变量改为闪烁次数更易理解这个算法。
1 #include
2 #include
3 using namespacestd;4 intmain(){5 intenergy,dis,time;6 cin >> energy >> dis >>time;7 int temp =time;8 int flash_cnt = 0;9 int s = 0;10 while(time > 0 and s = 10){13 flash_cnt++;14 energy-=10;15 }else energy+=4;16 s = max(s,flash_cnt*60);17 time--;18 }19 if(s >= dis)cout<
我还是太菜了........