Codeforces Round #642 (Div. 3) 参与排名人数11823
[codeforces 1353B] Two Arrays And Swaps 若数组a中最小值小于b中最大值,将其用b中最大值替换
总目录详见https://blog.csdn.net/mrcrack/article/details/103564004
在线测评地址http://codeforces.com/contest/1353/problem/B
Problem | Lang | Verdict | Time | Memory |
---|---|---|---|---|
B - Two Arrays And Swaps | GNU C++17 | Accepted | 31 ms | 3600 KB |
看了数据范围,一度以为要深搜dfs,在模拟样例的过程中,改变了想法。
思路如下:
若数组a中最小值小于b中最大值,将其用b中最大值替换;
若数组a中第二小的值小于b中第二大的值,将其用b中第二大的值替换;
若数组a中第三小的值小于b中第三大的值,将其用b中第三大的值替换;
以此类推。
样例模拟如下
2 1
1 2
3 4
排序后数组a 1 2
排序后数组b 4 3
替换后数组a 4 2
输出4+2=6
5 5
5 5 6 6 5
1 2 5 4 3
排序后数组a 5 5 5 6 6
排序后数组b 5 4 3 2 1
替换后数组a 5 5 5 6 6
输出5+5+5+6+6=27
5 3
1 2 3 4 5
10 9 10 10 9
排序后数组a 1 2 3 4 5
排序后数组b 10 10 10 9 9
替换后数组a 10 10 10 4 5
输出10+10+10+4+5=39
4 0
2 2 4 3
2 4 2 3
排序后数组a 2 2 3 4
排序后数组b 4 3 2 2
替换后数组a 2 2 3 4
输出2+2+3+4=11
4 4
1 2 2 1
4 4 5 4
排序后数组a 1 1 2 2
排序后数组b 5 4 4 4
替换后数组a 5 4 4 4
输出5+4+4+4=17
AC代码如下
#include <cstdio>
#include <algorithm>
using namespace std;
int a[35],b[35];
int cmp2(int a,int b){
return a>b;
}
int main(){
int t,n,k,i,sum;
scanf("%d",&t);
while(t--){
sum=0;
scanf("%d%d",&n,&k);
for(i=1;i<=n;i++)scanf("%d",&a[i]);
for(i=1;i<=n;i++)scanf("%d",&b[i]);
sort(a+1,a+1+n);//自小到大排序
sort(b+1,b+1+n,cmp2);//自大到小排序
for(i=1;i<=k;i++)
if(a[i]<b[i])swap(a[i],b[i]);//有则替换
else break;//无则不在进行替换
for(i=1;i<=n;i++)sum+=a[i];
printf("%d\n",sum);
}
return 0;
}