893C - Rumor - CodeForces Solution


dfs and similar graphs greedy *1300

Please click on ads to support us..

Python Code:

import sys,math,bisect
from functools import lru_cache
from random import randint
inf = float('inf')
mod = (10**9)+7
"========================================"
def nCr(n, r):
    return (fact(n) / (fact(r)
                * fact(n - r)))
def fact(n):
    res = 1
    for i in range(2, n+1):
        res = res * i
    return res
def lcm(a,b):
    return int((a/math.gcd(a,b))*b)
def gcd(a,b):
    return int(math.gcd(a,b))
def tobinary(n):
    return bin(n)[2:]
def binarySearch(a,x):
    i = bisect.bisect_left(a,x)
    if i!=len(a) and a[i]==x:
        return i
    else:
        return -1
def lowerBound(a, x):
    i = bisect.bisect_left(a, x)
    if i:
        return (i-1)
    else:
        return -1
def upperBound(a,x):
    i = bisect.bisect_right(a,x)
    if i!= len(a)+1 and a[i-1]==x:
        return (i-1)
    else:
        return -1
def primesInRange(n):
    ans = []
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    for p in range(2, n+1):
        if prime[p]:
            ans.append(p)
    return ans
def primeFactors(n):
    factors = set()
    while n % 2 == 0:
        factors.add(2)
        n = n // 2
    for i in range(3,int(math.sqrt(n))+1,2):
        while n % i== 0:
            factors.add(i)
            n = n // i
    if n > 2:
        factors.add(n)
    return factors
def isPrime(n,k=8):
    if (n <2):
        return True
    for i in range(0,k):
        a = randint(1,n-1)
        if(pow(a,n-1,n)!=1):
            return False
    return True
def find_closest(arr,target):
        arr.sort()
        min_diff = 1e19
        low = 0
        high = len(arr)-1
        closest_num = None

                if len(arr)==0:
            return None
                if len(arr)==1:
            return arr[0]

        while low <= high:
            mid = (low+high)//2
            min_diff_left = 1e19
            min_diff_right = 1e19
                        if mid +1 < len(arr):
                min_diff_right = abs(arr[mid+1]-target)


                        if mid -1 >= 0:
                min_diff_left = abs(arr[mid-1]-target)

            if min_diff_left < min_diff:
                min_diff = min_diff_left
                closest_num = arr[mid-1]

            if min_diff_right < min_diff:
                min_diff = min_diff_right
                closest_num = arr[mid+1]
            if arr[mid]<target:
                low = mid+1
            elif arr[mid]>target:
                high = mid-1
            else:
                return arr[mid]
        return closest_num
"========================================="

from collections import deque,defaultdict,Counter
from heapq import heappush, heappop,heapify
import string




for _ in range(1):
    n,m = map(int,input().split())
    cost = list(map(int,input().split()))
    graph = defaultdict(list)
    for _ in range(m):
        s,u = map(int,input().split())
        graph[s].append(u)
        graph[u].append(s)
    groups = []



    visited = set()
    for i in range(1,n+1):
        if i not in visited:
            curr = []
            Q = deque([i])
            while Q:
                s = Q.popleft()
                curr.append(s)
                visited.add(s)
                for nei in graph[s]:
                    if nei not in visited:
                        Q.append(nei)
            groups.append(curr)

    ans = 0

    for group in groups:
        curr = 1e19
        for i in group:
            curr = min(curr,cost[i-1])
        ans += curr
    print(ans)

C++ Code:

#include <iostream>
#include <bits/stdc++.h>
#include <numeric>
#include <algorithm>

typedef long long ll;

using namespace std;

class Person {
    public:
    ll m;
    vector<Person*> friends;
    int f = 0;
    bool visited = false;

    int Spread_Rumor(int min) {
        visited = true;
        //cout << m << endl;
        //cout << visited << endl;
        if (m < min) {
            min = m;
        }
        for (int i = 0; i < f; i++) {
            if (friends[i]->visited == false) {
                //cout << "Got here" << endl;
                min = friends[i]->Spread_Rumor(min);
            }
        }
        return min;
    }
};

int main() {
    int n, m;
    cin >> n >> m;
    vector<Person*> comm(n);
    ll p;
    for (int i = 0; i < n; i++) {
        cin >> p;
        Person* per = new Person();
        per->m = p;
        comm[i] = per;
    }
    int x, y;
    for (int i = 0; i < m; i++) {
        cin >> x >> y;
        comm[x-1]->friends.push_back(comm[y-1]);
        comm[x-1]->f++;
        comm[y-1]->friends.push_back(comm[x-1]);
        comm[y-1]->f++;
    }
    ll ans = 0;
    ans += comm[0]->Spread_Rumor(comm[0]->m);
    //cout << "Spreading rumor for first element, result is " << max << endl;
    int c;
    for (int i = 1; i < n; i++) {
        //cout << comm[i].f << endl;
        if (comm[i]->visited == false) {
            //cout << comm[i].visited << endl;
            //cout << "New Rumor:" << endl;
            c = comm[i]->Spread_Rumor(comm[i]->m);
            //cout << "Rumor for " << i+1 << " is " << c << endl;
            ans += c;
        }
    }
    cout << ans;
    return 0;
}


Comments

Submit
0 Comments
More Questions

1323. Maximum 69 Number
832. Flipping an Image
1295. Find Numbers with Even Number of Digits
1704. Determine if String Halves Are Alike
1732. Find the Highest Altitude
709. To Lower Case
1688. Count of Matches in Tournament
1684. Count the Number of Consistent Strings
1588. Sum of All Odd Length Subarrays
1662. Check If Two String Arrays are Equivalent
1832. Check if the Sentence Is Pangram
1678. Goal Parser Interpretation
1389. Create Target Array in the Given Order
1313. Decompress Run-Length Encoded List
1281. Subtract the Product and Sum of Digits of an Integer
1342. Number of Steps to Reduce a Number to Zero
1528. Shuffle String
1365. How Many Numbers Are Smaller Than the Current Number
771. Jewels and Stones
1512. Number of Good Pairs
672. Richest Customer Wealth
1470. Shuffle the Array
1431. Kids With the Greatest Number of Candies
1480. Running Sum of 1d Array
682. Baseball Game
496. Next Greater Element I
232. Implement Queue using Stacks
844. Backspace String Compare
20. Valid Parentheses
746. Min Cost Climbing Stairs