A. Rudolf and the Ticket:
Rudolf is going to visit Bernard, and he decided to take the metro to get to him. The ticket can be purchased at a machine that accepts exactly two coins, the sum of which does not exceed k.
Rudolf has two pockets with coins. In the left pocket, there are n coins with denominations b1,b2,…,bn. In the right pocket, there are mm coins with denominations c1,c2,…,cm. He wants to choose exactly one coin from the left pocket and exactly one coin from the right pocket (two coins in total).
Help Rudolf determine how many ways there are to select indices f and s such that bf+cs≤k
Input
The first line contains an integer t (1≤t≤100) — the number of test cases. Then follows the description of each test case.
The first line of each test case contains three natural numbers nn, mm, and kk (1≤n,m≤100,1≤k≤2000) — the number of coins in the left and right pockets, and the maximum sum of two coins for the ticket payment at the counter, respectively.
The second line of each test case contains nn integers bi (1≤bi≤1000) — the denominations of coins in the left pocket.
The third line of each test case contains mm integers ci (1≤ci≤1000) — the denominations of coins in the right pocket.
Output
For each testcase, output a single integer — the number of ways Rudolf can select two coins, taking one from each pocket, so that the sum of the coins does not exceed k.
题意:
有两个数组,分别是数组b和数组c,从数组b中挑选一个元素,从数组c中挑选一个元素,使得两个元素的和小于等于k,则满足条件,问满足条件的一共有多少种选法
解决方案:
使用暴力枚举的方案,一共是双重循环,时间复杂度是O(mn)。
代码实现:
#include<bits/stdc++.h>
using namespace std;
void solve()
{
int n,m,k; cin>>n>>m>>k;
vector<int> b(n);
vector<int> c(m);
for(int i=0;i<n;i++){
cin>>b[i];
}
for(int i=0;i<m;i++){
cin>>c[i];
}
int ans=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
ans+=b[i]+c[j]<=k; /// 这里解释一下,<=具有左结合性,会先计算b[i]+c[j]
///+= 操作符将 true 转换为 1(或者 false 转换为 0),并将其加到 ans 变量上。
}
}
cout<<ans<<endl;
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int t;
cin>>t;
while(t--)
{
solve();
}
return 0;
}