官方题解:
我用的是外层采用哈希,内层采用map的方式
其中有一个点就是一定要把所有的余数都取正,即(x%sum+sum)%sum,因为经过循环不仅可以往上加, 还可以向下减
就比如这个样例
1
2 2
-1 3
5
-5
正确答案应该是7 -1
但是如果余数不取正的话,第一个输出的结果就是-1了
代码如下:
#include <unordered_map>
//#include <unordered_set>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) (-x & x)
#define fi first
#define se second
#define PI acos(-1.0)
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int mod = 1e9 + 7;
const int N = 1e5 + 7;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
LL pre[N], q[N];
unordered_map<LL, map<LL, int>> mm;
inline void solve()
{
mm.clear();
int n, m; scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i ++ )
{
int x; scanf("%d", &x);
pre[i] = pre[i - 1] + x;
}
LL sum = pre[n];
if (sum == 0)
{
unordered_map<LL, int> tmp;
for (int i = 1; i <= n; i ++ )
{
if (!tmp[pre[i]]) tmp[pre[i]] = i;
}
while (m -- )
{
LL x; scanf("%lld", &x);
if (x == 0)
{
printf("0\n");
continue;
}
if (tmp[x]) printf("%d\n", tmp[x]);
else printf("-1\n");
}
return ;
}
for (int i = 0; i < m; i ++ ) scanf("%lld", &q[i]);
if (sum < 0)
{
for (int i = 1; i <= n; i ++ ) pre[i] *= -1;
for (int i = 0; i < m; i ++ ) q[i] *= -1;
sum *= -1;
}
for (int i = 1; i <= n; i ++ )
{
LL tmp = (pre[i] % sum + sum) % sum;
if (!mm[tmp][pre[i]])
mm[tmp][pre[i]] = i;
}
for (int i = 0; i < m; i ++ )
{
if (q[i] == 0)
{
printf("0\n");
continue;
}
LL tmp = (q[i] % sum + sum) % sum;
if (!mm.count(tmp))
{
puts("-1");
continue;
}
auto it = mm[tmp].upper_bound(q[i]);
if (it == mm[tmp].begin())
{
puts("-1");
continue;
}
it --;
LL ans = (q[i] - it->fi) / sum * n + it->se;
printf("%lld\n", ans);
}
}
int main()
{
int T; scanf("%d", &T);
while (T -- )
{
solve();
}
return 0;
}