题面:给出两个包含 n 个整数的数组 A,B。分别在 A, B 中任意出一个数并且相加,可以得到 n^2个和。求这些和中最小的 n 个。
输入格式
输入第一行一个整数n(1≤n≤50000)。接下来一行输入数组 A,用空格隔开。接下来一行输入数组 B,用空格隔开。1<=Ai, Bi<=10^9.
输出格式
从小到大输出最小的 n 个和,用空格隔开。
样例输入
4
1 3 5 7
2 4 6 8
样例输出
3 5 5 7
AC代码:
#include <cstdio> #include <algorithm> #include <iostream> #include <vector> using namespace std; int n, len; vector<int> v; int main(void) { cin >> n; int A[n], B[n]; for (int i=1;i<=n;i++) cin >> A[i]; for (int i=1;i<=n;i++) cin >> B[i]; sort(A+1, A+n+1); sort(B+1, B+n+1); for (int i = 1; i <= n; i++) for (int j = 1; i*j <= n; j++) v.push_back(A[i] + B[j]); sort(v.begin(), v.end()); printf("%d", v[0]); for (int i = 1; i < n; i++) printf(" %d", v[i]); printf(" "); return 0; }
这里附上一个写的很想详细的博主链接(本文部分思路来源):
https://blog.csdn.net/y20070316/article/details/50526422
#include <cstdio> #include <cctype> #include <queue> #include <algorithm> using namespace std; const int N=161240; int n; int A[N],B[N]; int lev[N]; inline int Read(void) { int s=0,f=1; char c=getchar(); for (;!isdigit(c);c=getchar()) if (c=='-') f=-1; for (;isdigit(c);c=getchar()) s=s*10+c-'0'; return s; } struct cmp { bool operator () (int i,int j) { return A[i]+B[lev[i]]>A[j]+B[lev[j]]; } }; priority_queue<int,vector<int>,cmp> q; int main(void) { n=Read(); for (int i=1;i<=n;i++) A[i]=Read(); for (int i=1;i<=n;i++) B[i]=Read(); sort(A+1,A+n+1); sort(B+1,B+n+1); fill(lev+1,lev+n+1,1); for (int i=1;i<=n;i++) q.push(i); int now; for (int i=1;i<=n;i++) { now=q.top(),q.pop(); printf("%d ",A[now]+B[lev[now]++]); q.push(now); } printf(" "); return 0; }
即为本文AC代码:
#include <cstdio> #include <cctype> #include <queue> #include <algorithm> using namespace std; const int N=161240; int n; int A[N],B[N]; int lev[N]; inline int Read(void) { int s=0,f=1; char c=getchar(); for (;!isdigit(c);c=getchar()) if (c=='-') f=-1; for (;isdigit(c);c=getchar()) s=s*10+c-'0'; return s; } struct cmp { bool operator () (int i,int j) { return A[i]+B[lev[i]]>A[j]+B[lev[j]]; } }; priority_queue<int,vector<int>,cmp> q; int main(void) { n=Read(); for (int i=1;i<=n;i++) A[i]=Read(); for (int i=1;i<=n;i++) B[i]=Read(); sort(A+1,A+n+1); sort(B+1,B+n+1); fill(lev+1,lev+n+1,1); for (int i=1;i<=n;i++) q.push(i); int now; for (int i=1;i<=n;i++) { now=q.top(),q.pop(); printf("%d ",A[now]+B[lev[now]++]); q.push(now); } printf(" "); return 0; }