1661A - Array Balancing - CodeForces Solution


greedy math

Please click on ads to support us..

Python Code:

def solve():
    n =int(input())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))
    sum = 0
    for i in range(len(a)):
        if a[i] > b[i]:
            b[i],a[i] = a[i],b[i]
    for i in range(len(a)-1):
        sum += abs(a[i] - a[i+1])
        sum += abs(b[i] - b[i+1])
    print(sum)
    
tst = int(input())
for i in range(tst):
    solve()

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<< #x <<" : "<<(x)<<endl;
#define dbgv(v) cout<< #v <<" : ";for(auto &i:v) cout<<(i)<<" ";cout<<endl;
void solve()
// int solve()
{
    int n;cin>>n;
    vector<int> a(n);
    int ans = 0,la = -1,lb=-1;
    for(int &i:a) cin>>i;
    for(int &i:a)
    {
        int x;cin>>x;
        int mx = max(x,i);
        int mn = min(x,i);
        if(la!=-1)
        {
            ans += abs(mx - la) + abs(mn - lb);
        }
        la = mx;
        lb = mn;
    }
    cout<<ans<<endl;
}
main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    cin>>t;
    while(t--)
    {
        solve();
        // cout<<solve()<<endl;
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

3B - Lorry
1392A - Omkar and Password
489A - SwapSort
932A - Palindromic Supersequence
433A - Kitahara Haruki's Gift
672A - Summer Camp
1277A - Happy Birthday Polycarp
577A - Multiplication Table
817C - Really Big Numbers
1355A - Sequence with Digits
977B - Two-gram
993A - Two Squares
1659D - Reverse Sort Sum
1659A - Red Versus Blue
1659B - Bit Flipping
1480B - The Great Hero
1519B - The Cake Is a Lie
1659C - Line Empire
515A - Drazil and Date
1084B - Kvass and the Fair Nut
1101A - Minimum Integer
985D - Sand Fortress
1279A - New Year Garland
1279B - Verse For Santa
202A - LLPS
978A - Remove Duplicates
1304A - Two Rabbits
225A - Dice Tower
1660D - Maximum Product Strikes Back
1513A - Array and Peaks