We need to read n vertices, m edges. Colors c_i (1 ≤ c_i ≤ 10^5). For each color k that appears (i.e., at least one vertex has that color), consider the set V(k) = {vertices with color k}. Then consider all edges from vertices in V(k) to other vertices (neighbors). From those neighbors, we collect the colors of those neighbor vertices (excluding the same color k? The definition: Q(k) = {c_u : c_u ≠ k and there is vertex v in V(k) such that nodes v and u are connected by an edge}. So Q(k) is set of distinct colors that appear on neighbors of vertices of color k, but only colors different from k. The cardinality of Q(k) is the "neighbouring color diversity". We need to find the color k (among those that appear) that maximizes |Q(k)|. If multiple have same maximum, output the smallest k.
Constraints: n,m up to 1e5, ci up to 1e5. So we need efficient computation.
We can iterate over edges. For each edge (u, v), let col_u = c[u], col_v = c[v]. If col_u != col_v, then for color k=col_u, neighbor color col_v contributes to Q(col_u). Similarly for k=col_v, neighbor color col_u contributes to Q(col_v). If col_u == col_v, then the edge connects two vertices of the same color, but since the neighbor's color is the same as k (c_u = k, c_v = k), then it's not counted (c_u ≠ k condition) => it does not contribute to Q(k). So only edges connecting vertices of different colors matter.
Thus we can process each edge (u,v) where c[u] != c[v]. For each such edge, we want to add to the set of neighbor colors for color c[u] the color c[v], and for color c[v] the color c[u]. But we need the size of the set, not just count of distinct neighbor colors. So we can maintain for each color, a set (or a hash set) of neighbor colors. But we need to handle up to 1e5 edges, and up to 1e5 distinct colors (potentially). However the total number of distinct neighbor entries per color might be large if we use sets naively? But each edge contributes at most 2 insertions into sets. So total possible insertions is 2m ≤ 2e5. So the total number of (color, neighbor color) pairs is bounded by 2m (if we store distinct). But we want distinct neighbor colors per color. So we can use hash sets (like unordered_set) per color. But there could be many colors (up to 1e5) and we don't want to allocate a set for colors that never appear. However, we can create map from color to a set (or to something). But we need to process edges and for each color we need to maintain a set of neighbor colors. Since total insertions is 2m, the total distinct pairs across all colors is at most 2m, but each pair may be duplicate if the same neighbor color appears multiple times via multiple edges. To avoid duplicates, we need to use a set. However we could also use counting: For each color, we could collect all neighbor colors from edges and then sort and unique, or use hash set. Since the sum of sizes of all neighbor color sets across all colors is O(m) if we consider that each edge may contribute two (color, neighbor) entries, but duplicates per color may reduce distinct count, but the total distinct pairs is at most total insertions? Actually each edge could produce the same pair (k, neighbor_color) multiple times if there are multiple edges between vertices of those colors. Since graph is simple, there is at most one edge between any pair of vertices. However, there could be multiple edges between different vertices of the same two colors, i.e., vertices of color k and vertices of color l, with many edges connecting various vertices of these colors. In that case, for color k, neighbor color l would appear from many edges, but we need to count it once. So we need deduplication. The total number of distinct (k, l) pairs (with k != l) that are adjacent via some edge is at most the number of unordered color pairs that have at least one edge between them. In worst case, if the graph is a complete bipartite? But m is at most 1e5, so the number of unordered pairs of vertices (edges) is at most 1e5. For each edge, it gives a pair of colors (c_u, c_v). So the number of distinct unordered color pairs from edges is at most m. And ordered pairs (k, l) are at most 2m distinct? Actually ordered pairs (k,l) with k != l are derived from each unordered pair (a,b): (a,b) and (b,a). So the total number of ordered distinct color pairs that appear is at most 2 * (number of unordered distinct color pairs). Since number of unordered distinct color pairs ≤ m, ordered ≤ 2m. So overall distinct (k, neighbor) entries across all colors are at most 2m (≤ 2e5). So it's manageable.
Thus we can create an unordered_map<int, unordered_set> neighbor_sets. For each edge (u,v) where c[u] != c[v], do neighbor_sets[c[u]].insert(c[v]); neighbor_sets[c[v]].insert(c[u]);
Then we need to find among colors that appear (i.e., there is at least one vertex with that color) the neighbor_sets[k].size() maximum. But careful: what if a color appears but has no neighbors of different color? Then its set may be empty. That's fine. We need to consider all colors that appear. Also note: neighbor_sets only contain colors for which there is at least one edge to a different color; if a color appears but has no incident edges or only edges to same color, neighbor_sets[k] might be empty (or not exist in the map). So we need to combine with the set of colors that appear (i.e., from c_i list). So we need to track all colors that appear: can collect in a set or array of size up to 1e5. Since ci ≤ 1e5, we can use a boolean array of size maybe 200000 to be safe. Actually max ci is 1e5, so we can use array of size 100001 or 100005.
But we need to output the color number that maximizes the diversity. If multiple, smallest.
Edge Cases: If a color appears but has no edges to other colors, its Q(k) = empty set size 0. The maximum may be 0. Then output smallest color that appears? But the problem says: "print the color with the minimum number." among those with maximum cardinality. So if all have 0, then smallest color that appears.
But also note: if there is at least one color, we need to output something.
Complexity: O(n + m) time plus some overhead for hash set operations. Since m up to 1e5, it's fine.
But need to watch out: using unordered_set per color could be heavy if we allocate many small sets. However total number of insert operations is 2m, and number of distinct colors is at most min(n, 1e5). So we could use a map from color to a set. But we can also use a more efficient approach: For each color, we can collect all neighbor colors (including duplicates) in a vector, then sort and unique across all colors at the end. But that would require storing possibly many duplicates: each edge contributes two entries, so total entries = 2m ≤ 2e5, which is fine. Then we could for each color, sort its vector and compute unique count. That might be simpler and avoid hash sets, but we need to map color to vector. Use unordered_map<int, vector>. Then after processing all edges, for each color, sort its vector, unique, and compute size. However sorting each vector individually might be less efficient if many colors have many entries, but overall total entries is 2e5, sorting each vector individually sums to O(sum(n_i log n_i)) which could be less than O(total log total) if we sort each separately? Actually sum(n_i log n_i) ≤ total log max_n_i? There's a bound: sum(n_i log n_i) ≤ total log total when each n_i ≤ total, but it's not necessarily less; it's at most total log total because each term n_i log n_i is ≤ n_i log total, sum = total log total. So overall O(total log total) which is fine for 2e5.
Alternatively, we can use unordered_set which is O(1) average. I'd go with unordered_set. But careful: In C++ unordered_set has overhead per insertion. It should be fine for 2e5.
However we also need to know which colors appear. We can simply read c_i and store them in an array or set. We'll also keep an array or unordered_set of colors that appear. Since max ci ≤ 100000, we can use a boolean array appear[100001] = false; Then when reading c_i, set appear[ci] = true. Also we need to handle colors that appear but have no neighbors: their neighbor set is empty. So we need to consider them.
Then after building neighbor_sets, we iterate over colors from 1 to maxColor (maybe up to 100000) but only those where appear[color] is true. For each, get the size of neighbor_sets[color] (if not present, size = 0). Keep track of max size and minimal color.
But caution: ci can be up to 1e5, but maybe some colors beyond that? Input says 1 ≤ ci ≤ 10^5, so max is 100000. So we can iterate up to 100000. That's fine.
But we also need to consider that there could be many colors that don't appear, but iterating over 100000 is fine.
Alternatively, we could store the list of distinct colors that appear, and iterate that list.
So algorithm:
- Read n, m.
- Read array c[1..n].
- Create bool appears[MAX_COLOR+1] = {false}, where MAX_COLOR = 100000 (maybe 100000 is enough, but to be safe 200000? I'll use 100001 inclusive). Also maybe find max_color to limit iteration.
- For i=1..n: appears[c[i]] = true.
- Create unordered_map<int, unordered_set> nb (or use map of int to set). We'll use unordered_map.
Alternatively, we could use vector<unordered_set> if we compress colors to indices, but not needed.
- For each edge (a,b):
Read a, b.
col_a = c[a], col_b = c[b].
if col_a != col_b:
nb[col_a].insert(col_b);
nb[col_b].insert(col_a);
- Initialize best_color = -1, best_size = -1.
- For color from 1 to MAX_COLOR (maybe up to 100000 or up to max color seen from c_i, but we can compute maxC while reading). But note: colors could be up to 100000, but we can also iterate over the keys in nb and also consider appears colors not in nb. So to be safe, we can iterate over all colors that appear (we have appears array) and maybe also over keys? We'll just loop from 1 to maxColor where maxColor = max(ci). Also need to consider that maybe there is a color > max(ci)? No. So compute maxColor = max(c_i).
- For color in 1..maxColor:
if appears[color]:
size = nb.count(color) ? nb[color].size() : 0;
if size > best_size or (size == best_size and color < best_color):
best_size = size; best_color = color;
- Print best_color.
But note: The graph may have up to 100000 vertices, but colors up to 100000; iterating up to 100000 is fine.
But what if some color > maxColor? No.
Check example 1:
n=6,m=6, colors: 1 1 2 3 5 8. Edges: (1-2) colors 1-1? Actually vertex 1 col1, vertex2 col1 -> same, ignore. (3-2) vertex3 col2, vertex2 col1 -> different -> nb[2].insert(1); nb[1].insert(2). (1-4) col1 - col3? Vertex1 col1, vertex4 col3 -> diff -> nb[1].insert(3); nb[3].insert(1). (4-3) col3 - col2 -> diff -> nb[3].insert(2); nb[2].insert(3). (4-5) col3 - col5 -> diff -> nb[3].insert(5); nb[5].insert(3). (4-6) col3 - col8 -> diff -> nb[3].insert(8); nb[8].insert(3). So nb[1] = {2,3} size 2; nb[2] = {1,3} size 2; nb[3] = {1,2,5,8} size 4; nb[5]={3} size 1; nb[8]={3} size1. Colors that appear: 1,2,3,5,8. So best is color 3 size4. Output 3 matches.
Second example: Colors: 4 2 5 2 4. Edges: (1-2):4-2 diff -> nb[4].insert(2); nb[2].insert(4); (2-3):2-5 diff -> nb[2].insert(5); nb[5].insert(2); (3-1):5-4 diff -> nb[5].insert(4); nb[4].insert(5); (5-3):4-5 diff? vertex5 col4, vertex3 col5 -> diff -> nb[4].insert(5) (already), nb[5].insert(4) (already); (5-4):4-2 diff -> nb[4].insert(2) already, nb[2].insert(4) already; (3-4):5-2 diff -> nb[5].insert(2) already, nb[2].insert(5) already. So nb[2] = {4,5} size2; nb[4] = {2,5} size2; nb[5]={2,4} size2. Colors appear: 2,4,5. All sizes 2. Minimum color is 2. Output 2 matches.
Seems fine.
Now we must consider constraints: n,m up to 1e5. Edges reading: O(m). Hash sets: each insertion average O(1). Memory: For each distinct color we have an unordered_set. The total number of stored neighbor colors across all sets is at most 2m distinct entries? Actually we store each inserted neighbor color but duplicates are prevented; but worst-case we may store up to number of distinct ordered color pairs. At most 2m. So memory O(m). That's fine.
Edge case: A color might have many distinct neighbor colors? Max distinct neighbor colors for a single color could be up to number of other colors that appear in the graph that are connected to that color. That could be up to total distinct colors - 1, which is up to 1e5. That's fine.
Implementation details:
-
Use 0-index or 1-index for vertices? We'll read 1-index and store c[1..n] in vector c(n+1).
-
We'll define MAXC = 100000 (or maybe 1000000? No, it says up to 1e5). But could there be ci > 1e5? The problem says 1 ≤ ci ≤ 10^5. So we can set constant 100000. However, it's safer to compute maxColor from input.
-
We'll use unordered_map<int, unordered_set> nb; But iterating over map keys later to compute best may be tricky because we need to include colors that appear but not in nb (size 0). So better to have the appear array and loop over colors.
But we need to consider that maxColor might be 100000, so iterating up to 100000 is fine. That's 100k iterations. So we can just do that.
Alternatively, we can maintain vector appearColors list, but then we need to also include colors not in nb, which we can just check if not in nb then size=0.
Implementation steps:
-
int n,m; cin >> n >> m;
-
vector c(n+1);
-
int maxColor = 0;
-
vector appears(100001, false); // but we need size 100001 because index up to 100000 inclusive
Actually we can make it dynamic: Since max ci maybe up to 100000, allocate 100001.
-
for (int i=1;i<=n;i++) { cin >> c[i]; appears[c[i]] = true; if (c[i] > maxColor) maxColor = c[i]; }
-
unordered_map<int, unordered_set> nb;
-
for (int i=0;i<m;i++) {
int a,b; cin >> a >> b;
int ca = c[a], cb = c[b];
if (ca != cb) {
nb[ca].insert(cb);
nb[cb].insert(ca);
}
}
-
int best_color = -1, best_size = -1;
-
for (int col = 1; col <= maxColor; col++) {
if (appears[col]) {
int sz = 0;
auto it = nb.find(col);
if (it != nb.end()) sz = it->second.size();
if (sz > best_size || (sz == best_size && col < best_color)) {
best_size = sz;
best_color = col;
}
}
}
-
cout << best_color << endl;
But wait: There is a subtle case: Suppose a color appears only on vertices that have no edges at all, then nb doesn't have that color, sz = 0. That's fine. Also suppose a color appears and has edges only to same color vertices, those edges are ignored, so sz=0.
Now, is it possible that maxColor is less than some color that appears? Actually we set maxColor as max of c_i. So it's fine.
But what if maxColor is 100000, then loop over 100000 is fine. But appears array size: we need at least maxColor+1. To be safe, we can set appears size to 100001. But if maxColor is 100000, we need index 100000, which is within 0..100000 inclusive, so size 100001. Good. However, to be generic, we could use vector appears with size 200001? But 100001 is enough as per constraints. Better to compute maxColor and allocate appears of size maxColor+1 dynamically.
So:
int maxColor = 0;
vector c(n+1);
for (i...) { cin >> c[i]; maxColor = max(maxColor, c[i]); }
vector appears(maxColor+1, false);
then after reading all, we can set appears as we go? Actually we need appears array sized after we know maxColor. We can first read all c's into vector, compute maxColor, then allocate appears of size maxColor+1 and fill. Or we can allocate a big array like 200000 to be safe. Since constraints are low, using 200000 or 100001 is fine. I'll just use a fixed array of size 100001 if I'm certain. However, ci can be up to 100000, so index 100000 is okay. We need to be careful if the environment's stack size is limited: global array of bool of size 100001 is small. Or we can use vector appear(100001). That's fine.
Let's adopt: const int MAXC = 100000; vector appear(MAXC+1, false); Then we need to make sure maxColor doesn't exceed 100000; it won't.
But there is also possibility that ci = 0? No, ci >= 1.
So implement.
Potential pitfalls: unordered_set may be slow for many small sets? But 2e5 insert operations, it's okay.
But we might also use unordered_map<int, vector> and then unique sort. However, using unordered_set may have overhead of rehashing if we insert many into one set. But worst-case: if graph is a star, center vertex of some color, and all leaves have distinct colors. Then the center color will have up to n-1 neighbor colors. That could be up to 1e5 distinct colors. Inserting 1e5 elements into unordered_set might be okay, but could cause rehashing. But still O(1e5). So it's okay.
Alternatively, we could compress neighbor colors by using a set (like std::set) but that would be log factor. unordered_set is fine.
But we must ensure we include <unordered_set> and <unordered_map>. Also use fast IO: ios_base::sync_with_stdio(false); cin.tie(nullptr).
Edge case: The graph has only one vertex, no edges. Then m=0. Colors appear: one color. neighbor set empty. best_color = that color. Output it.
Edge case: There are multiple colors that appear, all with zero neighbor diversity. Then we output smallest color among them.
Now test with sample 1: we did.
Now sample 2: we did.
Now check additional test: n=3,m=2; colors: 1 2 2; edges: 1-2,1-3. For color1: neighbor colors = {2} (since vertices 2 and 3 are both color2? Actually vertex1 col1 connects to vertex2 col2 and vertex3 col2, but both neighbor colors are 2, so set = {2} size1. Color2: vertices of color2 are vertex2 and vertex3; their neighbors: vertex2 connects to vertex1 (col1) -> neighbor color1; vertex3 connects to vertex1 (col1) -> also color1. So Q(2) = {1} size1. So both size1, min color=1. That's correct.
Now test with color having both same and different edges: e.g., n=4,m=3; colors: 1 1 2 3; edges: 1-2 (both color1 ignore), 1-3 (col1-col2 diff), 2-4 (col1-col3 diff). For color1: V(1) = vertices 1,2; edges from vertex1 to 3 (col2) and from vertex2 to 4 (col3). So Q(1) = {2,3} size2. color2: V(2) = {3}, neighbor: vertex1 (col1) -> {1} size1. color3: V(3) = {4}, neighbor: vertex2 (col1) -> {1} size1. So best=1. Implementation: nb[1] gets insert 2 from edge1-3? Actually we process edges: (1,2) same ignore. (1,3): ca=1, cb=2 => nb[1].insert(2); nb[2].insert(1). (2,4): a=2,b=4; ca=c[2]=1; cb=c[4]=3; diff => nb[1].insert(3); nb[3].insert(1). So nb[1]={2,3} size2; nb[2]={1} size1; nb[3]={1} size1. Good.
Now consider if there is a color that appears multiple times but also has self edges? Not possible because no self-loops. Edges between vertices of same color are ignored (they don't contribute to Q(k)). So it's correct.
Now think about performance: The map from int to unordered_set; we could use an array of vectors for neighbor colors if we compress colors to indices, but not needed.
But there is one nuance: The neighbor sets for a color may include colors that actually don't appear? Actually neighbor colors are colors of vertices adjacent; those vertices obviously exist and their color appears (since ci defined for all vertices). So they are in appear set. So it's fine.
Thus the algorithm is straightforward.
Now let's consider if there is any trick: The problem says "the color of the i-th vertex is an integer ci". It doesn't guarantee that ci are within small range? But given constraint is 1 ≤ ci ≤ 10^5, so it's fine.
Now we must implement in C++.
Potential memory: unordered_map<int, unordered_set> nb. For each color we have an unordered_set. That's overhead for each distinct color. Max distinct colors ≤ min(n, 1e5) ≤ 1e5. If we have 1e5 colors each with maybe tiny sets, the overhead could be high but still might be within memory limits (256 MB). Each unordered_set has some overhead (maybe a few pointers). For 1e5 colors that's okay. But if n is 1e5 and each vertex has unique color, then all colors appear. But edges m is 1e5, then total distinct neighbor pairs is at most 1e5, so many sets will be empty. However, we only create entries in nb for colors that have at least one neighbor of different color (i.e., for colors that appear on at least one endpoint of an edge with different color). So colors that appear but have no incident edges to other colors will not be in nb. That's fine. For colors that appear and are isolated, we won't create a set. So total number of keys in nb is at most number of colors that have at least one incident edge to a different color. That is at most number of vertices that are endpoints of cross-color edges? Actually a color could have many vertices, but at least one vertex with that color participates in a cross-color edge. So number of keys in nb is at most number of colors that have such edges. That could still be up to min(n, 1e5). In worst case, each vertex could have unique color and each vertex could be incident to at least one cross-color edge. Then each color appears exactly once and has at least one neighbor of different color, so nb will have up to n keys, each with a set. That is up to 1e5 sets. Each unordered_set might have small overhead. That could be high but probably within memory (e.g., each unordered_set object might be around 32 bytes or more). 1e5 * 32 = 3.2 MB, plus the elements. That's fine.
But implementation with unordered_map of unordered_set might be okay.
Alternatively, we can use a simpler approach: We could collect all edges where colors differ, and for each color, store a vector of neighbor colors, then sort and unique. This would avoid the overhead of many sets, but would require sorting. Both fine.
I'll go with unordered_map and unordered_set.
Now about input: Use scanf/printf for speed maybe. But cin with sync off is okay for 1e5.
Now check for potential integer overflow: none.
Now confirm we didn't miss something: The definition of Q(k) includes only neighbor vertices with color not equal to k. We have taken care by ignoring edges with same color. However, what if a vertex of color k has multiple neighbors of color l? Then we count l only once. That's handled by set.
Thus algorithm correct.
Now we should consider a possible edge: The graph may have isolated vertices (no edges). Then for their color, nb empty, best may be that color if it's the only one or if zero is max. That's fine.
Now we must ensure that for colors that appear but have no edges to other colors, they are considered with size 0.
Now I will write the code accordingly.
But there is an alternative approach: For each vertex, we can consider its incident edges and accumulate neighbor colors per color, but that would be similar.
Implementation plan:
#include <bits/stdc++.h>
using namespace std;
const int MAXC = 100000;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<int> c(n+1);
vector<bool> appear(MAXC+1, false);
int maxColor = 0;
for (int i = 1; i <= n; ++i) {
cin >> c[i];
appear[c[i]] = true;
if (c[i] > maxColor) maxColor = c[i];
}
unordered_map<int, unordered_set<int>> nb;
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
int ca = c[a], cb = c[b];
if (ca != cb) {
nb[ca].insert(cb);
nb[cb].insert(ca);
}
}
int best_color = -1, best_size = -1;
for (int col = 1; col <= maxColor; ++col) {
if (!appear[col]) continue;
int sz = 0;
auto it = nb.find(col);
if (it != nb.end()) sz = it->second.size();
if (sz > best_size || (sz == best_size && col < best_color)) {
best_size = sz;
best_color = col;
}
}
// In case best_color remains -1 (should not happen because appear at least one color)
if (best_color == -1) {
// fallback: find smallest color that appears
for (int col = 1; col <= maxColor; ++col) {
if (appear[col]) {
best_color = col;
break;
}
}
}
cout << best_color << endl;
return 0;
}
But note: we initialize best_color = -1, best_size = -1. When we encounter the first appearing color, its size may be 0, then condition: sz > -1 true, so it will be set. So best_color will be set to that first color (smallest?). Actually if we iterate col from 1 to maxColor, the first appearing color will be the smallest color that appears. But if its size 0, it becomes best. But later we may find a larger size, then best updates. If all sizes are 0, then after loop, best_color will be the smallest color that appears because we keep updating only when sz > best_size or (sz == best_size && col < best_color). Since initially best_size = -1, first appearing color sets best_size=0, best_color= that color. Later when we see another appearing color with size 0, condition sz == best_size (0) and col < best_color? Suppose first color is 5, later color 3 with size 0. Then sz==best_size && col<best_color -> true, so best_color becomes 3. So final best_color will be the smallest color with size 0. That's correct. So we don't need the fallback because at least one color appears. So we can skip fallback.
But careful: if appear array has all false? That would be impossible because n>=1. So fine.
Now we need to ensure that we don't exceed memory for nb. We used unordered_map<int, unordered_set>. Each unordered_set stores integers; we can also use unordered_map<int, vector> and then deduplicate after all edges. That would possibly reduce overhead of sets. But it's okay.
One more consideration: When we insert into nb[ca].insert(cb), if nb[ca] didn't exist before, it will default construct an empty unordered_set, then insert. That's fine.
Now test with bigger case: n=100000, each vertex unique color, m=100000 edges (random). Then nb will have up to 100000 keys each with maybe small sets. It's okay.
Time complexity: O(n + m + (total distinct neighbor color insertions) + (maxColor)). The insertions are O(1) average. So overall fine.
Now confirm the problem statement: "print the number of the color which has the set of neighbours with the maximum cardinality." It says "It there are multiple optimal colors, print the color with the minimum number." Good.
Now double-check sample 1: Should output 3.
Now sample 2: output 2.
Now code ready.
Potential improvements: Use vector appear size maybe 200001 to be safe if ci can be 100000. Already set MAXC=100000, but what if ci can be up to 10^5? That's fine. Actually 10^5 = 100000. So we need index 100000 inclusive; size = 100001. So define const int MAXC = 100000; vector appear(MAXC+1); That works.
But maybe there is a color 100000. Then appear[100000] is accessible (since size = 100001, indexes 0..100000). Yes.
Now for the loop for col from 1 to maxColor (which could be up to 100000). That's fine.
Now confirm that nb[ca] etc. works for ca up to 100000.
Now we can submit.
But caution: There is a nuance: In the problem, they use ci up to 10^5, but there could be colors with values greater than 10^5? The input constraints say 1 ≤ ci ≤ 10^5, so it's fine.
Now think about large memory for unordered_map. It might be okay.
Alternative: Use arrays indexed by color if we compress colors to consecutive IDs. But then we need to map original color to index. However, we would still need to track neighbor sets for each color; we could allocate vector<unordered_set> of size number of distinct colors (maybe up to 1e5). That's similar.
But we also need to know the original color number for output. So we could store for each distinct color its original value. So that approach is more work.
Thus keep it simple.
Now potential bug: When we read vertices a,b, we need to convert to 0-index or 1-index? We use 1-index for c. So a,b are 1-indexed. Good.
Now test with custom case: n=1,m=0, colors=[42]. Appear[42]=true; maxColor=42; nb empty. Loop col from 1 to 42, only col=42 appears; size=0; best_size=0, best_color=42; output 42. Good.
Now test: n=2,m=1, colors=[10,20], edge 1-2. nb[10]={20}, nb[20]={10}. appear[10]=true, appear[20]=true. Loop: col=1..20: 1-9 skip, col=10: size=1 best_size=1 best_color=10; col=20: size=1 but 20 > 10, so condition col<best_color? 20<10 false, so no update. So best_color=10. But both have size 1, smallest color is 10. That's correct.
Now test: n=2,m=1, colors=[20,10], edge 1-2. Then c[1]=20, c[2]=10. nb[20]={10}, nb[10]={20}. appears[20] and [10] true. Loop 1..20: first appearing? col=10 appears? yes, appears[10] true. So col=10 first encountered (since loop from 1 to 20). Then size=1, best_size=1, best_color=10. Then later col=20, size=1, but col=20 > best_color=10, so no update. So best_color=10. That's correct (smallest color). So our loop from low to high ensures we consider colors in increasing order; we only update when new color is smaller when sizes equal. So final result is smallest among those with max size. Good.
Now we can finalize.
But maybe there is a tricky point: The definition of Q(k) includes only neighbor colors that are different from k. But what if a vertex in V(k) has a neighbor of color k? That edge is not considered because c_u == k, so it's excluded. That's correct.
Now I think solution is correct.
Time complexity: O(n + m + (maxColor) ) where maxColor ≤ 100000. So overall < 3e5 operations plus hash insertions. Should pass.
But we could also implement using arrays of vectors and sorting:
unordered_map<int, vector<int>> nbv;
for each edge with different colors:
nbv[ca].push_back(cb);
nbv[cb].push_back(ca);
for(auto &p : nbv) {
sort(p.second.begin(), p.second.end());
p.second.erase(unique(...), p.second.end());
}
Then for each appearing color, we get size = nbv[col].size() if present else 0. That would also work and maybe avoid overhead of many small unordered_sets. But either is fine.
Let's consider the worst-case for sorting: If one color appears in many edges (like center color), its vector size could be up to degree (maybe up to 1e5). Sorting that is O(d log d) ~ 1e517 = 1.7e6, fine. But sum of sizes across all vectors is 2m = 2e5. So total sorting cost = sum_{col} (n_i log n_i) ≤ total * log(max_n_i) maybe ~ 2e517 = 3.4e6. That's also fine.
But with unordered_set, we don't need sorting, but we have hash overhead. Usually both are acceptable.
I'll stick with unordered_set for simplicity.
Now need to ensure we include necessary headers: #include #include #include <unordered_map> #include <unordered_set>. Using bits/stdc++.h is fine.
Now ensure to use 'int' for colors, up to 1e5 fits.
Now possible pitfall: The appears array of bool: we used vector which is a specialized bitset; accessing is fine. But we may also use vector for speed, but not needed.
Now check for potential wrong output if maxColor is less than some color due to nb keys? For example, suppose there is a color 100000 but we only allocated appear up to 100000? Actually we set MAXC=100000, and appear size = MAXC+1 = 100001, so index 100000 is valid. But if a color is 100000, maxColor will be 100000, so loop goes to 100000 inclusive, which is fine. So we need to ensure MAXC+1 includes 100000. 100000+1 = 100001. That's correct.
Now possible that ci can be 0? No.
Now finalize code.
But I recall a Codeforces problem "501B - Misha and Changing Handles"? No, this is maybe "Diversity of neighbors" or something. But anyway.
I'll produce final answer.
But before finalize, let's test with a scenario where there are colors > maxColor due to mapping? No.
Now ensure that we didn't forget to check if color appears but we later look for nb[col] via nb.find(col) - that's fine.
Now edge-case: nb[col] might be created even if the set is empty? Actually we create it only when we insert, and we only insert if ca != cb. So if a color appears but never has an edge to different color, nb won't have that key. So using find is correct.
Now consider colors that appear but have no incident edges to different colors: size=0.
Now also consider that there might be colors that appear but have only edges to same color: size=0.
Now I think it's fine.
Now I will produce final solution.
But perhaps there is an optimization: Since we need only the size, we could avoid storing the full set and instead use a map to count distinct neighbor colors? But set is simplest.
Now discuss potential pitfalls of unordered_set: If there are many colors (1e5) each with a small set, the overhead of the unordered_set object could be large. But we only create sets for colors that actually have at least one neighbor of different color. In worst-case, each vertex has unique color and each vertex is incident to at least one cross-color edge. Then nb will have up to n keys, each with at least one element. The memory for each unordered_set might be, say, 64 bytes (some implementations). 1e5 * 64 = 6.4 MB. Plus stored elements (each int 4 bytes) and maybe node overhead (for each element stored, there is a node with pointers and hash, could be 32 bytes). For each edge, we store two elements in two sets, so total elements stored (nodes) = 2 * number of edges? Actually each insertion tries to insert; if duplicate, no new node. But distinct ordered pairs could be up to 2 * number of unordered color pairs, which is at most 2m. So worst-case if each edge connects different colors and all pairs are distinct (no duplicate neighbor color for a given color), then each insertion adds a new element to a set. So total number of stored elements across all sets ≤ 2m = 2e5. Each element stored in unordered_set is a node with the integer and next pointer, maybe 16-32 bytes. 2e5 * 32 = 6.4 MB. So total maybe ~12 MB. That's fine.
But note: unordered_set in C++ standard library typically uses buckets and nodes; each insertion creates a node. So memory usage is okay.
Now we also have unordered_map overhead. Good.
Thus solution is acceptable.
Now final code:
I'll include comment and use fast IO.
Write in answer.
But the user asked: "You've got an undirected graph ..." They likely want a solution in some programming language, but not specified. Usually Codeforces problems expect C++ solutions. I'll provide C++ code.
Will produce final answer with explanation and code.
But the user message just says "You've got an undirected graph... Input ... Output ...". They likely want the solution. They didn't explicitly ask for code. But they likely expect solution explanation and code. We'll output code.
I will produce a final answer: explanation of algorithm and C++ code.
In the final response, I should include description and code.
Make sure to use proper formatting.
Now write final answer. We can solve the problem by processing all edges and maintaining, for each color that appears, the set of distinct neighboring colors (different from itself). Since each edge contributes at most two ordered pairs of colors, the total amount of information is O(m). After building these sets, we simply scan all colors that appear and select the one with the largest set size; ties are broken by the smallest color.
Algorithm:
- Read
n, m, and the colors c[1..n].
- Keep an array
appear (size up to 100001, because ci ≤ 10⁵) to mark which colors actually exist.
- For each edge
(a, b):
- If
c[a] != c[b], then add c[b] to the neighbor set of c[a] and add c[a] to the neighbor set of c[b]. Use a hash set per color to avoid duplicates.
- Iterate over all colors from 1 up to the maximum color that appears. For each color that is marked in
appear, compute the size of its neighbor set (0 if the set does not exist) and keep track of the best one (maximum size, minimum color in case of tie).
- Print the best color.
Time complexity: O(n + m + (max ci)) which is acceptable for n, m ≤ 10⁵. Memory: O(n + number of distinct color pairs) ≤ O(m + n).
C++ Implementation:
#include <bits/stdc++.h>
using namespace std;
const int MAXC = 100000; // according to constraints
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<int> c(n + 1);
vector<bool> appear(MAXC + 1, false);
int maxColor = 0;
for (int i = 1; i <= n; ++i) {
cin >> c[i];
appear[c[i]] = true;
if (c[i] > maxColor) maxColor = c[i];
}
unordered_map<int, unordered_set<int>> neighbours;
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
int ca = c[a], cb = c[b];
if (ca != cb) {
neighbours[ca].insert(cb);
neighbours[cb].insert(ca);
}
}
int bestColor = -1, bestSize = -1;
for (int col = 1; col <= maxColor; ++col) {
if (!appear[col]) continue;
int sz = 0;
auto it = neighbours.find(col);
if (it != neighbours.end()) sz = it->second.size();
if (sz > bestSize || (sz == bestSize && col < bestColor)) {
bestSize = sz;
bestColor = col;
}
}
cout << bestColor << '\n';
return 0;
}