C - Snuke Festival
Time limit : 2sec / Memory limit : 256MB
Score : 300 points
Problem Statement
The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.
He has N parts for each of the three categories. The size of the i-th upper part is Ai, the size of the i-th middle part is Bi, and the size of the i-th lower part is Ci.
To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.
How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.
Constraints
- 1≤N≤105
- 1≤Ai≤109(1≤i≤N)
- 1≤Bi≤109(1≤i≤N)
- 1≤Ci≤109(1≤i≤N)
- All input values are integers.
Input
Input is given from Standard Input in the following format:
N A1 … AN B1 … BN C1 … CN
Output
Print the number of different altars that Ringo can build.
Sample Input 1
2 1 5 2 4 3 6
Sample Output 1
3
The following three altars can be built:
- Upper: 1-st part, Middle: 1-st part, Lower: 1-st part
- Upper: 1-st part, Middle: 1-st part, Lower: 2-nd part
- Upper: 1-st part, Middle: 2-nd part, Lower: 2-nd part
Sample Input 2
3 1 1 1 2 2 2 3 3 3
Sample Output 2
27
Sample Input 3
6 3 14 159 2 6 53 58 9 79 323 84 6 2643 383 2 79 50 288
Sample Output 3
87
【题目大意】
搭祭坛,给出n个上层,中层,下层的尺寸。搭建要求由上到下尺寸严格递增。问可能的情况有多少(同层同尺寸的编号算作不同的)
【解题思路】
对上层,中层,下层尺寸进行排序,cnt[i]记录排序后第i个中层件可选的上层件数。这样我们可以知道。再遍历一遍下层,对每个下层件找到所对应的最大中层件,角标为m,则该下层件所对应的上、中层件搭配方案为 cnt[1]+cnt[2]+...+cnt[m],又易得,对下一个下层件所对应的中层件,角标为m1,m1>=m,需要再次求和。
发现可以通过前缀和的方式减小时间复杂度。
计算出每个中层件的上层搭配方案cnt[]后。
利用cnt[i+1]=cnt[i]+cnt[i+1],计算前缀和(一遍!省去多次循环重复计算)。
这时候对于每个下层件的搭配方案,为cnt[m](m为对应中层件的角标)。
【解题代码】
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e6+10;
int n,m,a[4][N];
ll ans,cnt[N];
int main()
{
// freopen("in.in","r",stdin);
// freopen("out.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=3;i++)
for(int j=1;j<=n;j++)
scanf("%d",&a[i][j]);
for(int i=1;i<=3;i++)
sort(a[i]+1,a[i]+n+1);
for(int i=1,j=1;j<=n;j++)
{
while(a[1][i]<a[2][j]&&i<=n) i++;
cnt[j]=i-1;
}
// for(int i=1;i<=n;i++)
// printf("cnt=%d\n",cnt[i]);
//改用前缀和(dp思想)
for(int i=1;i<=n-1;i++) cnt[i+1]=cnt[i]+cnt[i+1];
for(int i=1,j=1;j<=n;j++)
{
while(a[2][i]<a[3][j]&&i<=n) i++;
// for(int m=1;m<=i-1;m++)
// ans+=cnt[m] ;
ans+=cnt[i-1];
}
printf("%lld\n",ans);
return 0;
}
【收获与反思】
前缀和,多次循环计算时要利用,减小时间复杂度,不然就TLE了。。。