DHU&&面试安排

问题描述 :

公司计划面试 2N 人,这些人分布在全国各地。公司有两个城市可用于面试。

每个面试者飞到A市和B市的费用不一样,第 i 人飞往 A 市的费用为 costs[i][0],飞往 B 市的费用为 costs[i][1]。

现在需要你提出一个方案,将N个面试者分到A市,另外N个面试者分到B市,要求总的飞行费用最低。返回最低的总费用。

示例:

输入

2

10 20

30 200

400 50

30 20

输出: 110

解释:

第一个人去 A 市,费用为 10。

第二个人去 A 市,费用为 30。

第三个人去 B 市,费用为 50。

第四个人去 B 市,费用为 20。

最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有2个人在面试。

可使用以下main函数:

int main()
{
int N;
vector<vector<int> > costs;

cin>>N;

int costA,costB;

for(int i=0; i<2*N; i++)

{

    cin>>costA>>costB;

    vector<int> onePerson;

    onePerson.push_back(costA);

    onePerson.push_back(costB);

    costs.push_back(onePerson);

}

int res=Solution().CalcCost(costs);

cout<<res<<endl;

}

输入说明 :

首先输入N(面试者共有2N人),

然后输入2N行,每行两个整数a,、b,表示第i人飞往A市和B市的费用。

说明:

1 <= N <= 50

1 <= a, b <= 1000

输出说明 :

输出一个整数

输入范例 :

2
10 20
30 200
400 50
30 20

输出范例 :

110

解析:
贪心法:将差值比较大的先安排
map存储差值,key为差值,value为下标
一个城市安排满只后剩下全部安排到另一个。

代码:

#include<iostream>

#include<vector>

#include <algorithm>

#include<stack>

#include<map>

using namespace std;

class Solution {
public:

    int CalcCost(vector<vector<int>> &costs){
        multimap<int ,int> cmap;
        for(int i=0;i<costs.size();i++)
        {
            int a=abs(costs[i][0]-costs[i][1]);
            cmap.insert(pair<int,int >(a, i));
        }
        //遍历map
    multimap<int, int>::reverse_iterator   iter;
     int sum=0;
     int a=0;
     int b=0;
     //从大到小依次安排人员
     for(iter = cmap.rbegin(); iter != cmap.rend(); iter++){
          //cout<<iter->first<<"::"<<iter->second<<endl;
          int i=iter->second;
          //a满
          if(a==costs.size()/2)
          {
              sum+=costs[i][1];
              b++;
              continue;
          }
          //b满
          else if(b==costs.size()/2){
            sum+=costs[i][0];
            a++;
            continue;
          }
          //都不满a大,安排到b
          else if(costs[i][0]-costs[i][1]>0&&b<(costs.size())/2){
            b++;
            //cout<<costs[i][1]<<endl;
            sum+=costs[i][1];
          }
         else {
            a++;
            sum+=costs[i][0];
         }
     }
        return sum;
    }
};

int main()

{

    int N;

    vector<vector<int> > costs;

    cin>>N;

    int costA,costB;

    for(int i=0; i<2*N; i++)

    {

        cin>>costA>>costB;

        vector<int> onePerson;

        onePerson.push_back(costA);

        onePerson.push_back(costB);

        costs.push_back(onePerson);

    }

    int res=Solution().CalcCost(costs);

    cout<<res<<endl;

}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值