電腦學院大學生程式設計競賽(2015’12)The collector’s puzzle

來源:互聯網
上載者:User

標籤:

Problem DescriptionThere is a collector who own many valuable jewels. He has a problem about how to store them. There are M special boxes. Each box has a value. And each of the N jewels has a value too. 
The collector wants to store every jewel in one of the boxs while minimizing the sum of difference value. 
The difference value between a jewel and a box is: |a[i] - b[j]|, a[i] indicates the value of i-th jewel, b[j] indicates the value of j-th box.
Note that a box can store more than one jewel.
Now the collector turns to you for helping him to compute the minimal sum of differences. InputThere are multiple test cases.
For each case, the first line has two integers N, M (1<=N, M<=100000).
The second line has N integers, indicating the N jewels’ values.
The third line have M integers, indicating the M boxes’ values.
Each value is no more than 10000. OutputPrint one integer, indicating the minimal sum of differences. Sample Input4 41 2 3 44 3 2 14 41 2 3 41 1 1 1 Sample Output06

 我們先排序,然後以第二個數組為基礎,第一組的資料去查他們在第二組的位置

lower_bound
一共兩種情況,要麼剛剛好找到,一個在左邊
比如
2 3 4 5 7 尋找3 返回2
尋找 6 返回5 我們不知道它離左邊還是右邊差值小,可以都考慮進去
尋找8 返回最後一個位置
 
#include<stdio.h>//#include<bits/stdc++.h>#include<string.h>#include<iostream>#include<math.h>#include<sstream>#include<set>#include<queue>#include<map>#include<vector>#include<algorithm>#include<limits.h>#define MAXN (100000+10)#define MAXM (100000)#define inf 0x3fffffff#define INF 0x3f3f3f3f#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1#define LL long long#define ULL unsigned long longusing namespace std;int a[MAXN],b[MAXN];int main(){    int n,m;    while(cin>>n>>m)    {        int sum=0;        int i,j;        for(i=1;i<=n;i++)        {            cin>>a[i];        }        for(i=1;i<=m;i++)        {            cin>>b[i];        }        sort(a+1,a+n+1);        sort(b+1,b+m+1);        for(i=1;i<=n;i++)        {            int mid=inf;            int ans=lower_bound(b+1,b+m+1,a[i])-b;         //   cout<<ans<<endl;            if(ans<=m)            {                mid=min(mid,abs(a[i]-b[ans]));            }            if(ans>1)            {                mid=min(mid,abs(a[i]-b[ans-1]));            }            sum+=mid;        }        cout<<sum<<endl;    }    return 0;}

 

電腦學院大學生程式設計競賽(2015’12)The collector’s puzzle

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.