2021CCPC网络赛(重赛)Monopoly

官方题解:

我用的是外层采用哈希,内层采用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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值