Розбір
In this problem, we must find the union of two sets. This can be accomplished using either a set or a binary tree. Insert the values from all price labels into the chosen data structure, ensuring that it does not contain duplicate elements. For example, when using a binary tree, you should insert a new number only if it is not already present. Finally, print all the elements in ascending order.
Algorithm implementation
The values of the manufactured price tags will be inserted into the set .
set<int> s;
Read the input data. Insert price tags from the first supermarket into the set .
scanf("%d",&n); for(i = 0; i < n; i++) { scanf("%d",&val); s.insert(val); }
Insert price tags from the second supermarket into the set .
scanf("%d",&m); for(i = 0; i < m; i++) { scanf("%d",&val); s.insert(val); }
Print the contents of the set .
for (int x : s) printf("%d ", x); printf("\n");
Java implementation
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); TreeSet<Integer> s = new TreeSet<Integer>(); int n = con.nextInt(); while(n-- > 0) { int val = con.nextInt(); s.add(val); } n = con.nextInt(); while(n-- > 0) { int val = con.nextInt(); s.add(val); } // Iterator iter = s.iterator(); // for(int i = 0; i < s.size(); i++) // System.out.print(iter.next() + " "); for(int i : s) System.out.print(i + " "); con.close(); } }
Python implementation
Read the price lists from the first and second supermarkets.
n = int(input()) lst1 = list(map(int,input().split())) m = int(input()) lst2 = list(map(int,input().split()))
Convert the lists and into sets and perform a union operation on them ("or"). As a result, the list will contain unique prices from both supermarkets in arbitrary order.
res = list(set(lst1) | set(lst2))
Print the prices in ascending order.
print(*sorted(res))
Python implementation — set
The values of the manufactured price tags will be inserted into the set .
s = set()
Read price tags for the first supermarket and add them to the set .
n = int(input()) lst1 = list(map(int,input().split())) for x in lst1: s.add(x)
Read price tags for the second supermarket and add them to the set .
m = int(input()) lst2 = list(map(int,input().split())) for x in lst2: s.add(x)
Print the contents of the set in ascending order. Since sets in Python do not guarantee element order, use the sorted() function to ensure the elements are printed in ascending order.
for x in sorted(s): print(x, end=' ') print()