Divide and conquer:Moo University - Financial Aid(POJ 2010)

时间:2022-06-22 08:31:12

             Divide and conquer:Moo University - Financial Aid(POJ 2010)

                  Moo University - Financial Aid 

  其实是老题了http://www.cnblogs.com/Philip-Tell-Truth/p/4926008.html

  这一次我们换二分法来做这一道题,其实二分法比我以前那个方法好想一点,主要是这次我们可以根据下标进行二分,然后排两次序,第一次是根据分数来排序,然后记录分数的序,接下来就把aid排一次序,然后我们就可以进行二分了

  参考http://www.hankcs.com/program/cpp/poj-2010-moo-university-financial-aid-binary-search.html

  

 #include <iostream>
#include <algorithm>
#include <functional> using namespace std; struct _set
{
int score, aid, rank_score;
}Cows_Score[], Cows_Aid[];
bool rank_score(_set &a, _set &b)
{
return a.score < b.score;
}
bool aid_score(_set &a, _set &b)
{
return a.aid < b.aid;
} void solve(const int, const int, const int); int main(void)
{
int N, Cows_Sums, F; while (~scanf("%d%d%d", &N, &Cows_Sums, &F))
{
for (int i = ; i < Cows_Sums; i++)
scanf("%d%d", &Cows_Score[i].score, &Cows_Score[i].aid);
sort(Cows_Score, Cows_Score + Cows_Sums, rank_score);
for (int i = ; i < Cows_Sums; i++)
Cows_Score[i].rank_score = i;//给score的号排序,等一下二分的时候要用到
memcpy(Cows_Aid, Cows_Score, sizeof(_set)*Cows_Sums);
sort(Cows_Aid, Cows_Aid + Cows_Sums, aid_score); solve(N, Cows_Sums, F);
}
return ;
} void solve(const int N, const int Cows_Sums, const int F)
{
int lb = , rb = Cows_Sums, mid,left, right, tmp_sum;
bool m, n;
while (rb - lb > )//注意这里是对下标进行二分,对于aid直接找就可以了,注意一些细节上的问题就好
{
mid = (lb + rb) / ;
tmp_sum = Cows_Score[mid].aid;
left = ; right = ;
for (int i = ; i < Cows_Sums; i++)
{
if ((Cows_Aid[i].rank_score < mid) && (tmp_sum + Cows_Aid[i].aid <= F) && left < N / )
{
tmp_sum += Cows_Aid[i].aid;
left++;
}
else if ((Cows_Aid[i].rank_score > mid) && (tmp_sum + Cows_Aid[i].aid <= F) && right < N / )
{
tmp_sum += Cows_Aid[i].aid;
right++;
}
}
m = left < N / ? : ;
n = right < N / ? : ;
if (!m&&!n)
{
printf("-1\n");
return;
}
else if (m == || (m == && n == ))
lb = mid;
else if (n == )
rb = mid; }
printf("%d\n", Cows_Score[lb].score);
}

  Divide and conquer:Moo University - Financial Aid(POJ 2010)

  不过其实速度没差多少,因为都是O(nlogn)的算法