这里多次用到贪心的最优化选择和证明。
首先,T,t表示田忌最快马,和最慢马 ,K,k表示国王最快马,和最慢马。
若 T > K T与K组合,
若T < K t 与K组合。
若T == K,{
若 t <= k t与K 组合。
else t与k组合。
}
每一个都可以用任意交换不更差的方法证明。每一步都是对当前的贪心决策。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const int maxn = 11111;
int t[maxn],k[maxn];
int main()
{
int n;
while(scanf("%d",&n)==1&&n){
for(int i=0;i<n;i++)
scanf("%d",&t[i]);
for(int i=0;i<n;i++)
scanf("%d",&k[i]);
sort(t,t+n);
sort(k,k+n);
int T,K,tm,km;
int win = 0,tie=0,lose=0;
for(T=n-1,K=n-1,tm=0,km=0;T>=tm&&K>=km;){
if(t[T] > k[K]){
win++; T--; K--;
}
else if(t[T]<k[K]){
lose++; tm++; K--;
}
else{
if(t[tm]<=k[km]){
if(t[tm] < k[K]) lose++;
tm++; K--;
}
else {
win++; tm++; km++;
}
}
}
printf("%d\n",(win-lose)*200);
}
return 0;
}
本文通过田忌赛马的经典问题介绍了一种基于贪心策略的解决方案,并提供了详细的算法实现。通过对比不同马匹的速度来决定比赛策略,确保了在有限的选择中获得最优结果。
305

被折叠的 条评论
为什么被折叠?



