Under construction

Still being built. Things may change

Adventurer Guilds

Interview

Time limit3sMemory limit1024 MB

Summary
Guilds merge into alliances and gain or lose adventurers, and each query asks for the total adventurers in the alliance shared by two guilds, or -1 if none.
Level

Medium4 of 10

Topics
Union-find, Array
Solved
No attempts yet

Problem

Adventurer guilds numbered 11 to NN exist. An adventurer can join or leave a guild freely. At the start, each guild forms its own alliance, so there are NN alliances in total.

When guild aa and guild bb form an alliance, the alliance containing aa and the alliance containing bb merge into one new alliance. The guilds get along well, so an alliance is never dissolved.

The guild headquarters holds a celebration party each time two guilds first end up in the same alliance. A party can be held at any time, and the same pair of guilds may hold several parties. The party for guilds aa and bb includes all guilds in the alliance that contains both of them at the moment they first share an alliance. The headquarters needs to know how many people attend each party to plan the budget.

Suppose the guilds in that alliance at that moment are g1,g2,…,gkg_1, g_2, \dots, g_k. Let f(gi)f(g_i) be the number of adventurers in guild gig_i at the time the party is held. The number of attendees is f(g1)+f(g2)+⋯+f(gk)f(g_1) + f(g_2) + \dots + f(g_k).

Process the following queries in order.

  • 11 ii xx: xx adventurers join guild ii. (1≤i≤N1 \le i \le N, 1≤x≤1091 \le x \le 10^9)
  • 22 ii xx: xx adventurers leave guild ii. Guild ii is guaranteed to have at least xx adventurers. (1≤i≤N1 \le i \le N, 1≤x≤1091 \le x \le 10^9)
  • 33 aa bb: guilds aa and bb form an alliance. (1≤a,b≤N1 \le a, b \le N, a≠ba \ne b)
  • 44 aa bb: print the number of attendees if guilds aa and bb held a party now. If guilds aa and bbhave never been in the same alliance, print −1-1. (1≤a,b≤N1 \le a, b \le N, a≠ba \ne b)

Input

The first line contains the number of guilds NN (2≤N≤300 0002 \le N \le 300\,000) and the number of queries QQ (1≤Q≤300 0001 \le Q \le 300\,000).

The second line contains the initial number of adventurers in each guild, G1,G2,…,GNG_1, G_2, \dots, G_N. (1≤Gi≤1091 \le G_i \le 10^9)

The next QQ lines each contain one query as described above.

All input values are integers.

Output

For each query of type 44, print the answer on its own line.

Examples3

  1. Example 1

    Input
    4 8
    3 4 5 6
    3 1 2
    3 2 3
    3 3 4
    2 1 2
    4 1 2
    4 1 3
    2 2 3
    4 2 3
    
    Expected output
    5
    10
    7
    
  2. Example 2

    Input
    4 3
    3 4 5 6
    1 3 5
    4 1 2
    3 1 2
    
    Expected output
    -1
    
  3. Example 3

    Input
    4 6
    3 4 5 6
    3 1 2
    3 2 3
    2 1 2
    4 1 2
    1 2 3
    4 1 2
    
    Expected output
    5
    8