## 「CodeForces 1198F」GCD Groups 2

You are given an array of 𝑛 integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.

You are given an array of 𝑛 integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.

This is the harder version of the problem. In this version, 1≤𝑛≤106 and 0≤𝑎𝑖≤106. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems

Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare 𝑛 boxes of chocolate, numbered from 1 to 𝑛. Initially, the 𝑖-th box contains 𝑎𝑖 chocolate pieces.

There are 𝑛 seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to 𝑛 from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat 𝑖 (1≤𝑖≤𝑛) will decide to go for boiled water at minute 𝑡𝑖.

Tank with a boiled water is located to the left of the 1-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly 𝑝 minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small.

The only difference between easy and hard versions is constraints.

Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.

There are 𝑛 voters, and two ways to convince each of them to vote for you. The first way to convince the 𝑖-th voter is to pay him 𝑝𝑖 coins. The second way is to make 𝑚𝑖 other voters vote for you, and the 𝑖-th voter will vote for free.

Moreover, the process of such voting takes place in several steps. For example, if there are five voters with 𝑚1=1, 𝑚2=2, 𝑚3=2, 𝑚4=4, 𝑚5=5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: 5→1,5→1,2,3,5→1,2,3,4,5.