问题 F: 选择(set二分+前缀和)

问题 F: 选择(set二分+前缀和)

题目描述

哈哈哈,快忘掉你的烦心事,找张位子坐下来。
beny和fife两人作为彼此炉边好友,决定来一场惊心动魄的友谊(py)赛。
fife有n个随从,第i个随从有一个能力值,为A[i]。
beny也有对应的n个随从,第i个随从同样也有一个能力值,为B[i]。
然后,一群随从的战斗力为这群随从能力值的总和。
现在,beny和fife每个人都派出自己第L个到第R个(共R-L+1个随从),来一决高下。
但是由于他们在一绝高下的同时要py任务,他们要你选择一对(L,R),使双方战斗力差距最小。
他们要你输出最小的战斗力差距(战斗力较大的减战斗力较小的)。

输入

第一行一个正整数n。
第二行n个整数,表示数组A。
第三行n个整数,表示数组B。

输出

一行一个正整数, 表示最小的战斗力差距。

样例输入 Copy

【样例1】
3
4 2 3
3 4 2
【样例2】
5
38 19 5 17 3
15 22 0 6 17

样例输出 Copy

【样例1】
0
【样例2】
1

提示

样例1解释:L = 1, R = 3
样例2解释:L = 2, R = 5

思路:求两数组差的前缀和,然后每次从set里找最接近c[i]的两个数,一个比从c[i]大,一个比从c[i]小。更新最小值。

#pragma comment(linker, "/STACK:1024000000,1024000000")
#pragma GCC optimize(3,"Ofast","inline")
#include <bits/stdc++.h>
 
using namespace std;
 
#define rep(i , a , b) for(register int i=(a);i<=(b);i++)
#define per(i , a , b) for(register int i=(a);i>=(b);i--)
#define ms(s) memset(s, 0, sizeof(s))
#define squ(x) (x)*(x)
#define fi first
#define se second
 
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll , ll> pi;
typedef unordered_map<int,int> un_map;
typedef priority_queue<int> prque;
 
template<class T>
inline void read (T &x) {
    x = 0;
    int sign = 1;
    char c = getchar ();
    while (c < '0' || c > '9') {
        if ( c == '-' ) sign = - 1;
        c = getchar ();
    }
    while (c >= '0' && c <= '9') {
        x = x * 10 + c - '0';
        c = getchar ();
    }
    x = x * sign;
}
 
const int maxn = 3e5 + 10;
const int inf = 1e9;
const ll INF = ll(1e18);
const int mod = 998244353;
const double PI = acos(-1);
//#define LOCAL
 
int n;
ll c[maxn];
ll a[maxn];
ll b[maxn];
set<ll>p;
set<ll>::iterator it;
void solve() {
    rep(i,1,n) {
        read(a[i]);
    }
    rep(i,1,n) {
        read(b[i]);
        c[i]=a[i]-b[i];
        c[i]=c[i-1]+c[i];
    }
    p.insert(0);
    p.insert(INF);
    ll ans = INF;
    rep(i,1,n) {
        it = p.upper_bound(c[i]);
        ll y = *it;
        it--;
        ll x = *it;
        ans=min(ans,abs(c[i]-y));
        ans=min(ans,abs(c[i]-x));
        p.insert(c[i]);
    }
    printf("%lld\n",ans);
}
 
int main(int argc, char * argv[])
{
    #ifdef LOCAL
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    #endif
     
    while(~scanf("%d",&n)) {
        solve();
    }
    return 0; 
}
发布了259 篇原创文章 · 获赞 2 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/dy416524/article/details/105733983