比较好的一个贪心题目。
题目:田忌赛马
思路:
采用的贪心策略是:
1、田忌的快马比齐王的快,直接比掉。
2、若快马没有快,拿田忌最慢的和齐王最慢的比较,若快直接比掉。
3、若慢马比齐王慢,就拿田忌最慢的和齐王最快的比较。
(原来的思路是对两个数组排序,遍历国王的马,只要找到一个大于他的就加一。。。。结果WA,原谅还怎么会用贪心,用JAVA写太麻烦了)
import java.util.*;
/*
* 贪心策略
* 1、田忌的快马比齐王的快,直接比掉。
* 2、若快马没有快,拿田忌最慢的和齐王最慢的比较,若快直接比掉。
* 3、若慢马比齐王慢,就拿田忌最慢的和齐王最快的比较。
*
* */
public class Main {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n;
int qquick,tquick,qslow,tslow;
long[] T = new long[1001];
long[] Q = new long[1001];
while(true)
{
int money = 0;
int eq = 0;
n = in.nextInt();
if(n == 0) break;
for(int i=0; i<n; i++)
{
T[i] = in.nextLong();
}
for(int i=0; i<n; i++)
Q[i] = in.nextLong();
insertSort(T,n);
insertSort(Q,n);
int j=n-1, k=0, l=n-1, m=0;
while(j>=k)
{
if(T[j]>Q[l])//最快的和最快的比较
{
j--;
l--;
money+=200;
}
else if(T[j]<Q[l]){
k++;
l--;
money -= 200;
}
else if(T[k]>Q[m]){//最慢的和最慢的比较
k++;
m++;
money += 200;
}
else{
if(T[k]<Q[l])//最慢的和最快的比较
money -= 200;
k++;
l--;
}
}
System.out.println(money);
}
}
public static void insertSort(long[] a,int nElems)
{
int in,out;
for(out=1; out<nElems; out++)
{
long temp = a[out];
in = out;
while(in>0 && a[in-1] >= temp)
{
a[in] = a[in-1];
--in;
}
a[in] = temp;
}
}
}