1475D - Cleaning the Phone - CodeForces Solution


binary search dp sortings two pointers *1800

Please click on ads to support us..

Python Code:

for _ in range(int(input())):
    n,m = map(int,input().split())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))
    x = []
    y = []
    for i in range(n):
        if b[i] == 1:
            x.append(a[i])
        else:
            y.append(a[i])
    x.sort(reverse=True)
    y.sort(reverse=True)
 
    t, cost = 0, 0
    p2 = -1
    ans = 210000000000
    while p2+1 < len(y) and t < m:
        p2 += 1
        t += y[p2]
        cost += 2
    if t >= m:
        ans = min(ans, cost)
    for i in range(len(x)):
        t += x[i]
        cost += 1
        while p2 >= 0 and t-y[p2]>=m:
            t -= y[p2]
            p2 -= 1
            cost -= 2
        if t >= m:
            ans = min(ans,cost)
    if ans >= 210000000000:
        print(-1)
    else:
        print(ans)

C++ Code:

#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int num = 2e5 + 10,maNum = 1e9 + 5;
int ma, mi,ol,x, y, z, m, p, q, k;
int t, n, i, j;//循环变量
long long sum, ans;
int a[num];
set<int> box;
bool flag;
string s;
char ch;
vector<int> b, c;
#define pii pair<int,int>
int main()
{
	cin >> t;
	while(t--){
		b.clear(), c.clear();
		sum = 0;
		cin >> n >> m;
		for (i = 1; i <= n; i++)
		{
			cin >> a[i];
			sum += a[i];
		}
		for (i = 1; i <= n; i++)
		{
			cin >> k;
			if (k == 1)
			{
				b.push_back(a[i]);
			} else
			{
				c.push_back(a[i]);
			}
		}
		if (sum < m)
		{
			cout << -1 << endl;
			continue;
		}
		sort(b.begin(), b.end(), greater<int>());
		sort(c.begin(), c.end(), greater<int>());
		p = 0, q = 0;
		x = b.size() - 1, y = c.size() - 1;
		ans = 0;
		while (m > 0)
		{
			if (p <= x && m <= b[p])
			{
				ans++;
				m -= b[p];
				p++;
				break;
			}
			k = b[p] + b[p + 1];
			if (p < x && (q > y || (k > c[q])))
			{
				p += 2;
				m -= k;
			} else
			{
				m -= c[q];
				q++;
			}
			ans += 2;
		}
		m *= -1;
		for (i = p - 1; i >= 0; i--)
		{
			if (m >= b[i])
			{
				ans--;
				m -= b[i];
			} else break;
		}
		cout << ans << endl;
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

550B - Preparing Olympiad
939B - Hamster Farm
732A - Buy a Shovel
1220C - Substring Game in the Lesson
452A - Eevee
1647B - Madoka and the Elegant Gift
1408A - Circle Coloring
766B - Mahmoud and a Triangle
1618C - Paint the Array
469A - I Wanna Be the Guy
1294A - Collecting Coins
1227A - Math Problem
349A - Cinema Line
47A - Triangular numbers
1516B - AGAGA XOOORRR
1515A - Phoenix and Gold
1515B - Phoenix and Puzzle
155A - I_love_username
49A - Sleuth
1541A - Pretty Permutations
1632C - Strange Test
673A - Bear and Game
276A - Lunch Rush
1205A - Almost Equal
1020B - Badge
1353A - Most Unstable Array
770A - New Password
1646B - Quality vs Quantity
80A - Panoramix's Prediction
1354B - Ternary String