zoukankan      html  css  js  c++  java
  • 配对(思维)

    链接:https://ac.nowcoder.com/acm/contest/3007/A
    来源:牛客网

    题目描述

    现在有正整数集合 A 和 B,每个集合里有 N 个数,你要建立他们间的一一映射
    将每对配对的数字相加可以得到 N 个和,你要做的就是最大化第 K 大的和
    1≤K≤N≤100,000 输入的所有数字不超过 108

    输入描述:

    第一行 2 个数字 N,K
    接下来两行,每行 N 个正整数,分别表示 A 和 B 中的元素

    输出描述:

    一行,表示第 K 大的和的最大值

    输入

    3 2
    1 2 3
    1 2 3

    输出

    5


    官方题解:

    我们要使得第K大的和尽可能大,显然可以贪心:
    首先,组成这K对数字的显然是操作A中最大的K个数字和B中最大的K个数字。
    问题转化为怎样配对使得最小的和最大:
    我们发现,如果A1<A2,B1<B2,那么一定是由A1和B2配对较优。
    经过简单的归纳可以得到,倒序配对是最优的,这样就解决了问题。
     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <iostream>
     4 #include <string>
     5 #include <math.h>
     6 #include <algorithm>
     7 #include <vector>
     8 #include <stack>
     9 #include <queue>
    10 #include <set>
    11 #include <map>
    12 #include <sstream>
    13 const int INF=0x3f3f3f3f;
    14 typedef long long LL;
    15 const double eps =1e-8;
    16 const int mod=1e9+7;
    17 const int maxn=1e5+10;
    18 using namespace std;
    19 
    20 int a[maxn];
    21 int b[maxn];
    22 
    23 int main()
    24 {
    25     #ifdef DEBUG
    26     freopen("sample.txt","r",stdin);
    27     #endif
    28     
    29     int n,m; 
    30     scanf("%d %d",&n,&m);
    31     for(int i=1;i<=n;i++)
    32         scanf("%d",&a[i]);
    33     for(int i=1;i<=n;i++)
    34         scanf("%d",&b[i]);
    35     sort(a+1,a+1+n);
    36     sort(b+1,b+1+n);
    37     int ans=INF; 
    38     for(int i=n;i>n-m;i--)
    39         ans=min(ans,a[i]+b[n+n-m+1-i]);
    40     printf("%d
    ",ans);
    41     
    42     return 0;
    43 }

    -

  • 相关阅读:
    图文详解QT布局管理器
    osg中放大缩小模型
    osgearth中XML文档读取报错
    中国河南省洛阳市嵩县黄庄乡红堂村大树芽组
    GIS数据下载整合
    四面体剖分相关开源软件列表
    在你的QT工程中使用ui文件
    对osgAnimation例子的注释的注释
    [debug]调试Release版本应用程序
    链表面试题总结
  • 原文地址:https://www.cnblogs.com/jiamian/p/12319295.html
Copyright © 2011-2022 走看看