Monopoly (数学,数据结构,同余域)

题目链接

在这里插入图片描述
Code:

#include<bits/stdc++.h>
#define int long long
#define endl '\n' 
#define br putchar('\n') 
#define _x fixed << setprecision
#define debug(x) cerr<< #x << '=' << x << '\n'
#define ok() cout << "Yes\n" 
#define gg() cout << "No\n" 
#define mem(a, b) memset(a, b, sizeof(a));
#define rep(i, a, b) for (int i = a;i <= b; ++i)
#define rrep(i, a, b) for(int i = a; i >= b; --i)
#define ALL(a) (a).begin(), (a).end()
#define IOS ios::sync_with_stdio(false); cin.tie(0);cout.tie(0)
using namespace std;
typedef pair<int, int> PII;
int dx[] = {-1, 0, 1, 0, -1, 1, 1, -1}, dy[] = {0, 1, 0, -1, 1, 1, -1, -1};
const int N = 100010;

int n, m, a[N], pre[N], sum;

map<int, vector<PII> >mp;
map<int, int> mp_pre;

void solve_0()
{
    for(int i = 1; i <= n; ++i) 
        if(!mp_pre[pre[i]]) mp_pre[pre[i]] = i;
    while(m -- )
    {
        int x; cin >> x;
        if(x == 0) cout << 0 << endl;
        else cout << (mp_pre[x] == 0 ? -1 : mp_pre[x]) << endl;
    }
}

void solve()
{
    bool ok = false;
    if(sum < 0) {
        ok = true;
        sum = -sum;
        for(int i = 1; i <= n; ++i) pre[i] = -pre[i];
    }
    // 同余域,后面要找到该域里面前缀和最大的位置,所以存储相反数,升序排序,二分查找第一个大于等于的位置
    for(int i = 1; i <= n; ++i)
    {
        int y = (pre[i] % sum + sum ) % sum;
        mp[y].push_back({-pre[i], i});
    }
    for(auto &it : mp)
        sort(ALL(it.second));
    while( m -- )
    {
        int x; cin >> x;
        x = ok ? -x : x;
        if(x == 0) cout << 0 << endl;
        else
        {
            int xx = (x % sum + sum ) % sum;
            if(mp.find(xx) == mp.end()) cout << "-1\n";
            else
            {
                PII pos = {-x, 0};
                int id = lower_bound(ALL(mp[xx]), pos) - mp[xx].begin();
                if (id == mp[xx].size()) cout << "-1\n";
                else 
                {
                    int ans = mp[xx][id].second;
                    ans += (x + mp[xx][id].first) / sum * n;
                    cout << ans << endl;
                }
            }
        }
    }
}

signed main(){
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    IOS;
    int tt; cin >> tt;
    while( tt -- )
    {
        mp.clear(), mp_pre.clear();
        cin >> n >> m;
        sum = 0;
        for(int i = 1; i <= n; ++i){
            cin >> a[i];
            pre[i] = a[i] + pre[i - 1], sum += a[i];
        }
        sum == 0 ? solve_0() : solve();
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

W⁡angduoyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值