Problem Link
#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
const int N = 100001;
int arr[N];
vector<pair<int, int> > range;
int preK[N]; // ith position store number of values equal to k till index i
int preK1[N]; // ith position store number of values equal to k + 1 till index i
void resetArray()
{
range.clear();
for(int i = 0; i < N; i++)
{
arr[i] = 0;
preK[i] = preK1[i] = 0;
}
}
int main()
{
int t, n, k, l, r, count, maxCount, maxN, i;
cin >> t;
while(t--)
{
scanf("%d%d", &n,&k);
count = maxCount = maxN = 0;
resetArray();
for(i = 1; i <= n; i++)
{
scanf("%d%d", &l,&r);
range.push_back(make_pair(l, r));
maxN = max(maxN, r);
arr[l] += 1;
if(r + 1 < N)
{
arr[r + 1] -= 1;
}
}
// build array from range updates
for(i = 1; i <= maxN; i++)
{
count += arr[i];
arr[i] = count;
}
for(i = 1; i <= maxN; i++)
{
preK[i] = preK[i - 1] + (arr[i] == k ? 1 : 0);
preK1[i] = preK1[i - 1] + (arr[i] == k + 1 ? 1 : 0);
}
int s = range.size();
for(i = 0; i < s; i++)
{
l = range[i].first;
r = range[i].second;
// count will be equal to number of K in range [0, l - 1] +
// number of K + 1 in range [l, r] +
// number of K in range [r + 1, n]
count = preK[l - 1] + preK1[r] - preK1[l - 1] + preK[maxN] - preK[r];
maxCount = max(maxCount, count);
}
printf("%d\n", maxCount);
}
return 0;
}
#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
const int N = 100001;
int arr[N];
vector<pair<int, int> > range;
int preK[N]; // ith position store number of values equal to k till index i
int preK1[N]; // ith position store number of values equal to k + 1 till index i
void resetArray()
{
range.clear();
for(int i = 0; i < N; i++)
{
arr[i] = 0;
preK[i] = preK1[i] = 0;
}
}
int main()
{
int t, n, k, l, r, count, maxCount, maxN, i;
cin >> t;
while(t--)
{
scanf("%d%d", &n,&k);
count = maxCount = maxN = 0;
resetArray();
for(i = 1; i <= n; i++)
{
scanf("%d%d", &l,&r);
range.push_back(make_pair(l, r));
maxN = max(maxN, r);
arr[l] += 1;
if(r + 1 < N)
{
arr[r + 1] -= 1;
}
}
// build array from range updates
for(i = 1; i <= maxN; i++)
{
count += arr[i];
arr[i] = count;
}
for(i = 1; i <= maxN; i++)
{
preK[i] = preK[i - 1] + (arr[i] == k ? 1 : 0);
preK1[i] = preK1[i - 1] + (arr[i] == k + 1 ? 1 : 0);
}
int s = range.size();
for(i = 0; i < s; i++)
{
l = range[i].first;
r = range[i].second;
// count will be equal to number of K in range [0, l - 1] +
// number of K + 1 in range [l, r] +
// number of K in range [r + 1, n]
count = preK[l - 1] + preK1[r] - preK1[l - 1] + preK[maxN] - preK[r];
maxCount = max(maxCount, count);
}
printf("%d\n", maxCount);
}
return 0;
}
Comments
Post a Comment