题解:AT_abc466_f [ABC466F] Many Mod Calculation
可惜,赛时STL选错了。
首先,取模操作是有序的,如果先模一个较小的数,再模一个较大的数,那么后一次操作就没有意义了。用式子表示就是如果
现在来推正解。我们从余数的角度思考。假设
那如果
******* 0
******* 4
******* * 3
******* * 2
******* * 1
^
rest=3=38%5
余数为
现在还是看不出什么,但当你再次操作,比如
******* 4 mod 3 = 1
******* * 3 mod 3 = 0 -> ans
******* * 2 mod 3 = 2
******* * 1 mod 3 = 1
^
rest=3
这时,余数为
这样我们就做完了...吗?
除完
******* 4 mod 3 = 1
******* * 2 mod 3 = 2
******* * 1 mod 3 = 1
余数
但是想到第一次,我们将除不尽的数记为了余数,与大块分开计算,我们同样可以将这个多出来的块记为余数。只不过这一次,余数块有了大小。重新定义余数块为
******* * 2
******* * & 1 (& 表示那里有7个,是一个块)
最终,我们得到了每次处理后真正的答案:
答案过后的处理,则是要将大块合成小块:
此外,如果
余数的块可以用set优先队列维护,以
然后此题得解。
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 2e5+5 , mod = 998244353 ;
int a[N] , x , n , ans = 0 , m , b[N] ;
struct node{
int x , num ;
bool operator < ( const node &t )const{
return x < t.x ;
}
};
priority_queue < node > q ;
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int T ;
cin >> T ;
while( T -- )
{
cin >> n >> m ;
cin >> x ;
int pnum = m/x , p = x-1 ;
ans = pnum ;
while( !q.empty() ) q.pop() ;
if( m%x != 0 ) q.push( { m%x , 1 } ) ;
for( int i = 2 ; i <= n ; i ++ )
{
cin >> x ;
if( x > p ) continue ;
int nnum = (p/x)*pnum ;
ans += nnum ;
while( !q.empty() )
{
int nx = q.top().x , xnum = q.top().num ;
if( nx < x ) break ;
q.pop() ;
ans += (nx/x)*xnum ;
nnum += (nx/x)*xnum ;
if( nx % x != 0 ) q.push( { nx%x , xnum } ) ;
}
if( p%x != 0 ) q.push( { p%x , pnum } ) ;
pnum = nnum ;
p = x-1 ;
}
cout << ans << "\n" ;
}
return 0;
}
复杂度分析
这才是此题最唬人的地方。如果每次操作都会产生一次余数块,那么总块数就到了
对于每一个块考虑。当前块被处理当且仅当
很明显,每次操作后,