题意:
有1-n个节点,从0出发,每次只能往右走一个节点,n的下一步会回到1节点,每走到一个节点获得ai(-1e9-1e9)点分数,m次查询,每次查询最少走多少步分数可以到达x。
思路:
令从1-n走完一轮的总分数为sum
根据每个点的前缀和对sum取余得到的值分组,然后每次查询二分查找x对sum取余同余的那组最优的节点,没有则说明没有合法点
思路不难想,赛中一开始想歪了,后面纠正回来的时候没多少时间了,在写法上一直在犹豫,最后成功把自己送走。
#include<bits/stdc++.h>
#define LL long long
using namespace std;
typedef pair<LL,LL>pa;
const int N = 1e5+7;
LL n, _, x, m, sum, cnt, f;
LL a[N], s[N];
map<LL, LL> mp;
map<LL, LL> mp1;
map<pa, bool> mmp;
struct node{
LL mo, val, idx;
bool operator < (const node &x) const{
if(mo==x.mo){
if(val==x.val)
return idx<x.idx;
else
return val<x.val;
}
else return mo<x.mo;
}
};
vector<node> v1[N];
void sol1(){
for(LL i = 1;i <= cnt;i++){
sort(v1[i].begin(), v1[i].end());
}
while(m--){
scanf("%lld", &x);
LL y;
if(x>=0) y = x%sum;
else y = x%sum+sum;
LL id = mp[y];
if(!id){
printf("-1\n");
continue;
}
node tem = {y, x, 1ll*10000000000000};
int pos = upper_bound(v1[id].begin(), v1[id].end(), tem)-v1[id].begin()-1;
if(pos<=-1){
printf("-1\n");
continue;
}
if(v1[id][pos].mo==y){
printf("%lld\n", (x-v1[id][pos].val)/sum*n + v1[id][pos].idx);
} else {
printf("-1\n");
}
}
}
void sol2(){
for(LL i = 1;i <= cnt;i++){
sort(v1[i].begin(), v1[i].end());
}
while(m--){
scanf("%lld", &x);
LL y;
if(x<=0) y = x%sum;
else y = x%sum+sum;
LL id = mp[y];
if(!id){
printf("-1\n");
continue;
}
node tem = {y, x, -1ll * 100000000000000};
int pos = lower_bound(v1[id].begin(), v1[id].end(), tem)-v1[id].begin();
if(pos>=v1[id].size()){
printf("-1\n");
continue;
}
if(v1[id][pos].mo==y){
printf("%lld\n", (x-v1[id][pos].val)/sum*n + v1[id][pos].idx);
} else {
printf("-1\n");
}
}
}
int main(){
scanf("%lld", &_);
while(_--){
mp.clear();mp1.clear();mmp.clear();
scanf("%lld%lld", &n, &m);
sum = 0ll;
for(int i = 1;i <= n;i++){
v1[i].clear();
scanf("%lld", &a[i]);
sum += a[i];
if(!mp1[sum])
mp1[sum] = i;
s[i] = sum;
//printf("sum = %lld\n", sum);
}
if(!sum){
while(m--){
scanf("%lld", &x);
if(!x) printf("0\n");
else if(mp1[x]){
printf("%lld\n", mp1[x]);
} else {
printf("-1\n");
}
}
continue;
}
if(sum>0){
cnt = 0ll;
for(LL i = 0;i <= n;i++){
if(s[i]>=0)
f = s[i]%sum;
else
f = s[i]%sum + sum;
if(!mp[f])
mp[f] = ++cnt;
if(!mmp[{f, s[i]}]){
v1[mp[f]].push_back({f, s[i], i});
mmp[{f, s[i]}] = 1;
}
}
sol1();
}
else if(sum<0){
cnt = 0ll;
for(LL i = 0;i <= n;i++){
if(s[i]<=0)
f = s[i]%sum;
else
f = s[i]%sum + sum;
if(!mp[f])
mp[f] = ++cnt;
if(!mmp[{f, s[i]}]){
v1[mp[f]].push_back({f, s[i], i});
mmp[{f, s[i]}] = 1;
}
}
sol2();
}
}
return 0;
}