-
题目描述
标题:递增三元组
给定三个整数数组
A = [A1, A2, ... AN],
B = [B1, B2, ... BN],
C = [C1, C2, ... CN],
请你统计有多少个三元组(i, j, k) 满足:
1. 1 <= i, j, k <= N
2. Ai < Bj < Ck
【输入格式】
第一行包含一个整数N。
第二行包含N个整数A1, A2, ... AN。
第三行包含N个整数B1, B2, ... BN。
第四行包含N个整数C1, C2, ... CN。
对于30%的数据,1 <= N <= 100
对于60%的数据,1 <= N <= 1000
对于100%的数据,1 <= N <= 100000 0 <= Ai, Bi, Ci <= 100000
【输出格式】
一个整数表示答案
【样例输入】
3
1 1 1
2 2 2
3 3 3
【样例输出】
27
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
注意:
main函数需要返回0;
只使用ANSI C/ANSI C++ 标准;
不要调用依赖于编译环境或操作系统的特殊函数。
所有依赖的函数必须明确地在源文件中 #include <xxx>
不能通过工程设置而省略常用头文件。
提交程序时,注意选择所期望的语言类型和编译器类型。
-
解题代码及要点(注释中)
//暴力求解
/*#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int num;
scanf("%d", &num);
int a[num], b[num], c[num];
//输入
for(int j = 0; j < num; j++){
scanf("%d", &a[j]);
}
for(int j = 0; j < num; j++){
scanf("%d", &b[j]);
}
for(int j = 0; j < num; j++){
scanf("%d", &c[j]);
}
int count = 0;
for(int i = 0; i < num; i++){
for(int j = 0; j < num; j++){
for(int k = 0; k < num; k++){
if(a[i]<b[j]&&b[j]<c[k]){
count++;
}
}
}
}
cout<<count;
return 0;
}
*/
//暴力求解可能会翻车。使用快排+基于二分的定位法解决问题。
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int main()
{
int num;
scanf("%d", &num);
int a[num], b[num], c[num];
//输入
for(int j = 0; j < num; j++){
scanf("%d", &a[j]);
}
for(int j = 0; j < num; j++){
scanf("%d", &b[j]);
}
for(int j = 0; j < num; j++){
scanf("%d", &c[j]);
}
sort(a, a+num);
sort(b, b+num);
sort(c, c+num);
int count = 0;
for(int i = 0; i < num; i++){
//求出数组a中第一个等于或大于b[i]的位置,该位置正好是
//数组a中小于b[i]的元素个数。
int x = lower_bound(a, a+num, b[i])-a;
//求出数组c中第一个大于b[i]的位置,该位置正好对应着数
//组c中小于或等于b[i]的元素个数。num-该个数恰好是数组
//c中大于b[i]的元素个数。
int y = num-(upper_bound(c, c+num, b[i])-c);
count += x*y;
}
cout<<count;
return 0;
}
-
总结
1. sort函数,功能:实现快速排序的效果。
--时间复杂度为:n*log2(n)。头文件是#include <algorithm>。
--用法:sort(a, a+n); 即sort(数组名,数组大小)。
--相传编写一个返回值为bool的函数作为第三个参数,可以实现逆序排列的效果。
2. 用到了lower_bound函数和upper_bound函数。原理为二分法。
--lower_bound函数的功能:用来确定数组中第一个与给定参数相等,或比给定参数大的元素的位置。
--用法【lower_bound(a, a+n, key)-a】。a为数组名字,n为数组大小,key为给定参数。
--upper_bound函数的功能:用来确定数组中第一个比给定参数大的元素的位置。没错,lower_bound函数和upper_bound函数的区别就这么点。
--用法【upper_bound(a, a+n, key)-a】。a为数组名字,n为数组大小,key为给定参数。