Codevs2157 配对

 

题目描述 Description

   给出2个序列A={a[1],a[2],…,a[n]},B={b[1],b[2],…,b[n]},从A、B中各选出n个元素进行一一配对(可以不按照原来在序列中的顺序),并使得所有配对元素差的绝对值之和最大。

输入描述 Input Description

输入的第1行为1个整数n
第2行包含n个整数,题目中的A序列。 
第3行包含n个整数,题目中的B序列。

输出描述 Output Description

一个数,最大配对

样例输入 Sample Input

4
2 5 6 3
1 4 6 7

样例输出 Sample Output

14

数据范围及提示 Data Size & Hint

3与6配对,2与7配对,5与4配对,6与1配对,绝对值之差和为14

对于10%的数据,有n≤20; 
对于30%的数据,有n≤100; 
对于50%的数据,有n≤1000; 
对于100%的数据,有n≤10000;a[i],b[i]≤1000。

 
分析规律可知,一个数组升序排序,另一个数组降序排序,然后相同位置的配对,得到的答案最大。
同理,两数组都升序或都降序排序,同位置配对,得到的答案最小。
 1 /*by SilverN*/
 2 #include<algorithm>
 3 #include<iostream>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<cmath>
 7 #include<vector>
 8 using namespace std;
 9 const int mxn=100010;
10 int read(){
11     int x=0,f=1;char ch=getchar();
12     while(ch<'0' || ch>'9'){if(ch=='-')f=-1;ch=getchar();}
13     while(ch>='0' && ch<='9'){x=x*10+ch-'0';ch=getchar();}
14     return x*f;
15 }
16 int n;
17 int a[mxn],b[mxn];
18 int cmp(int a,int b){return a>b;}
19 int main(){
20     int i,j;
21     n=read();
22     for(i=1;i<=n;i++)a[i]=read();
23     for(i=1;i<=n;i++)b[i]=read();
24     sort(a+1,a+n+1);
25     sort(b+1,b+n+1,cmp);
26     long long ans=0;
27     for(i=1;i<=n;i++){
28         ans+=abs(a[i]-b[i]);
29     }
30     cout<<ans<<endl;
31     return 0;
32 }

 

posted @ 2016-11-03 16:00  SilverNebula  阅读(294)  评论(0编辑  收藏  举报
AmazingCounters.com