Adventurer Guilds
InterviewTime limit3sMemory limit1024 MB
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 to exist. An adventurer can join or leave a guild freely. At the start, each guild forms its own alliance, so there are alliances in total.
When guild and guild form an alliance, the alliance containing and the alliance containing 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 and 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 . Let be the number of adventurers in guild at the time the party is held. The number of attendees is .
Process the following queries in order.
- : adventurers join guild . (, )
- : adventurers leave guild . Guild is guaranteed to have at least adventurers. (, )
- : guilds and form an alliance. (, )
- : print the number of attendees if guilds and held a party now. If guilds and have never been in the same alliance, print . (, )
Input
The first line contains the number of guilds () and the number of queries ().
The second line contains the initial number of adventurers in each guild, . ()
The next lines each contain one query as described above.
All input values are integers.
Output
For each query of type , print the answer on its own line.