922D - Robot Vacuum Cleaner - CodeForces Solution


greedy sortings *1800

Please click on ads to support us..

Python Code:

import heapq
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

n = int(input())
h = []
inf = pow(10, 9) + 1
ans = 0
for _ in range(n):
    t = list(input().rstrip())
    c = [0] * 2
    x = 0
    for i in t:
        c[i & 1] += 1
        if not i & 1:
            ans += c[1]
    if not c[0]:
        heapq.heappush(h, (0, c[1], c[0]))
    elif not c[1]:
        heapq.heappush(h, (inf, c[1], c[0]))
    else:
        heapq.heappush(h, (c[0] / c[1], c[1], c[0]))
c = 0
while h:
    _, u, v = heapq.heappop(h)
    ans += c * v
    c += u
print(ans)

C++ Code:

#include<bits/stdc++.h>
using namespace std;
const long long maxn=1e5+5;
long long n,ans,sans,s[maxn],h[maxn],value[maxn],id[maxn];
char a[maxn];
bool cmp(long long ida,long long idb);
long long cost(long long a,long long b);
int main(){
	scanf("%lld",&n);
	for(long long i=1;i<=n;i++){
		scanf("%s",(a+1));
		for(long long j=1,len=strlen(a+1);j<=len;j++){
			if(a[j]=='s')s[i]++;
			else value[i]+=s[i],h[i]++;
		}
		id[i]=i;
	}
	sort(id+1,id+1+n,cmp);
	for(long long i=1;i<=n;i++){
		ans+=value[id[i]]+sans*h[id[i]];
		sans+=s[id[i]];
	}
	printf("%lld",ans);
	return 0;
}
bool cmp(long long ida,long long idb){
	return cost(ida,idb)>cost(idb,ida);
}
long long cost(long long a,long long b){
	return value[a]+value[b]+s[a]*h[b];
}


Comments

Submit
0 Comments
More Questions

946. Validate Stack Sequences
921. Minimum Add to Make Parentheses Valid
881. Boats to Save People
497. Random Point in Non-overlapping Rectangles
528. Random Pick with Weight
470. Implement Rand10() Using Rand7()
866. Prime Palindrome
1516A - Tit for Tat
622. Design Circular Queue
814. Binary Tree Pruning
791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST
445. Add Two Numbers II
442. Find All Duplicates in an Array
437. Path Sum III
436. Find Right Interval
435. Non-overlapping Intervals
406. Queue Reconstruction by Height
380. Insert Delete GetRandom O(1)
332. Reconstruct Itinerary