answer
The key is to find out recycling section
For me, cycling festival this question not engage in, the big brother to teach, I finally will, and quickly take down a small notebook.
First, if before we find circulation section, k value dimming, and direct output frequency
if there is not,
Suppose y-times selected to the number of a [k% n], is a time, referred to as the x-th, once the first 1 ~ y-1 in the time
that the x-th to y times the operation is a loop section,
Since K X and K Y same remainder after mod n (the same as may be selected from A), minus the same quantity, the number of the next I will be the same,
Find cycling holiday, to find the lowest point in the cycle section of k,
because k Adding and Subtracting constantly updated, if you want to be the first y operations, the lowest point k value must be greater than or equal to 0, otherwise it is impossible the next step
Statistical operations x ~ y weight value, referred to as sum [x ... y],
if the operating cycle weights and sum> = 0, less than 0. K Save never directly outputs -1
and vice versa, can be calculated directly formulas the need to go through how many cycles Festival, at the end of the little remaining components can not be a loop section, direct violence statistics
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
int n;
int v[N];
ll a[N],sum[N],k;
int main(){
ios::sync_with_stdio(0);
int T;
cin>>T;
sum[0]=0;
for (int cs = 1; cs <= T; ++cs) {
cin>>n>>k;
for (int i = 0; i <n; ++i) {
cin>>a[i];
v[i]=0;
sum[i+1]=0;
}
ll cnt=0,x,s;//这里的s不赋值也没事 如果在找到位置之前k小于0 后面的判断的时候k+m也是小于0的
//找循环节
while(k>=0){
x=k%n;
if(v[x]){//找到第一个曾经到过的位置
s=v[x];
break;
}
sum[cnt+1]=sum[cnt]+a[x];
k+=a[x];
cnt++;
v[x]=cnt;
}
ll m=0;
for (int i = s; i <= cnt; ++i) {
m=min(m,sum[i]-sum[s-1]);//找到能通过循环的最小值
}
if(k+m<0){//如果当前的k加上下一个循环节里的m
while(k>=0){//如果k还有剩余 继续往下跑(没准是在m之前就减光了呢)
x=k%n;
k+=a[x];
cnt++;
}
cout<<cnt<<endl;
}else if(sum[cnt]-sum[s-1]>=0){//呈现增加的趋势
cout<<"-1"<<endl;
}else{//再给一次循环还是不够 还需要多减几次循环节
ll ans=(k+m)/(sum[s-1]-sum[cnt])*(cnt-s+1)+cnt;
//k+m 表示可以通过循环的部分
//sum[s-1]-sum[cnt] 表示每次经过循环减少的值
//+cnt 记得把之前统计的也加上
k=(k+m)%abs(sum[cnt]-sum[s-1])-m;//统计剩余的k
//这里减m是因为前面是以k+m计算的 多加了要剪掉(当然m是负数 也可以说是多减了再加回去)
while(k>=0){
x=k%n;
k+=a[x];
ans++;
}
cout <<ans << endl;
}
}
return 0;
}