现在的位置: 首页 > 综合 > 正文

ZOJ 3508 贪心算法

2018年03月17日 ⁄ 综合 ⁄ 共 1689字 ⁄ 字号 评论关闭

DescriptionA war had broken out because a sheep from your kingdom ate some grasses which belong to your neighboring kingdom. The counselor of your kingdom had to get prepared for this war. There are N (1 <= N <= 2500) unarmed soldier in your kingdom and there
are M (1 <= M <= 40000) weapons in your arsenal. Each weapon has a weight W (1 <= W <= 1000), and for soldier i, he can only arm the weapon whose weight is between minWi and maxWi ( 1 <= minWi <= maxWi <= 1000). More armed soldier means higher success rate
of this war, so the counselor wants to know the maximal armed soldier he can get, can you help him to win this war?InputThere multiple test cases. The first line of each case are two integers N, M. Then the following N lines, each line contain two integers
minWi, maxWi for each soldier. Next M lines, each line contain one integer W represents the weight of each weapon.OutputFor each case, output one integer represents the maximal number of armed soldier you can get.Sample Input3 31 53 75 104892 25 1010 20421Sample
Output20

思路 :如果不进行一定的排序,就从头开始为每个soldier分配一个武器,不一定是最优解;

方法 ; 每个区间[a,b]; 先按b升序排序,再按a降序排序; 然后逐个遍历每个区间;(策略 

 x[2,4 ],   y[1,4 ], z[2, 7];

若有一个点在4位置,肯定要优先分给x,因为即使最优解中将4分给y或z,将之分给x不会丢失最优解,而翻过来不成立,若只有两点4,7存在则将点4分

给z,则这三个区间的最终配对为一,不是最优解;)

#include <algorithm>
#include <iostream>
#include <cstring>
#include <climits>
#include <cstdio>
#include <string>
#include <vector>
#include <cmath>
#include <cctype>
#include <deque>
#include <queue>
#include <list>
#include <map>
#include <set>
using namespace std;
const int maxn=2500 + 10;

struct Sol{
int a,b;
bool operator < (const Sol& rhs) const{
return b<rhs.b||b==rhs.b&&a > rhs.b;
}
}sol[maxn];
int w[maxn],N,M;
int main()
{
    while(cin>>N>>M)
    {
        for(int i=0;i<N;i++) cin>>sol[i].a>>sol[i].b;
        memset(w,0,sizeof(w));
        for(int i=0;i<M;i++)
        {
            int x; cin>>x;
            w[x]++;
        }
        sort(sol,sol+N);
        int num=0;
        for(int i=0;i<N;i++)
        {
            for(int j=sol[i].a;j<=sol[i].b;j++)
            {
                if(w[j])
                {
                    w[j]--;
                    num++;
                    break;
                }
            }
        }
        cout<<num<<endl;
    }
}
【上篇】
【下篇】

抱歉!评论已关闭.