1389D 2100的水题。。。
题意:给你一个n表示操作次数,k表示重合区间长度,然后两个区间分别为[l1,r1],[l2,r2],操作为对其中任意一个区间进行增长任意次,增长一个单位ans++,当这个操作完成之后,区间变为原来的,然后进行下一次操作。
思路:就是模拟两个区间的重合位置,分两种情况,
如果r1<l2,即两个区间没有交集,要对操作次数进行枚举,因为有可能你操作次数多了还不如直接两步一个交集
如果r1>=l2,即两个区间有交集,虽然说等于的时候是没有的,但可以看成是有,无伤大雅。这个就简单多了,直接算。
具体实现看代码。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i < n; i++)
#define per(i, a, n) for(int i = n-1; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
#define PI 3.14159265358979323846
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 1e5+10;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
return x*f;
}
ll cal(ll li, ll k, ll n){
ll cnt = 0;
if(li*n >= k) cnt += k;
else {
k -= li*n;
cnt += (li*n + 2*k);
}
return cnt;
}
inline void cf(){
ll t = read();
while(t--){
ll n=read(), k=read();
ll l1=read(), r1=read(), l2=read(), r2=read();
if(l2<l1) swap(l1,l2), swap(r1,r2);
ll ans = 0;
if(r1>=l2){
ll in = abs(l2-min(r1,r2)); //交集部分
ll li = max(r1, r2)- l1 -in; //没有相交部分
if(k>n*in) printf("%lld\n", cal(li, k-n*in, n)); //如果小于的话直接进行n次操作就能达到交集区间大于k,反之要进行扩充,当成l2=r1来看
else printf("0\n");
}else{
ll d = l2-r1, cnt = onf; //d为两个区间有交集时要走的步数
for(int i = 1; i <= n; i++) cnt = min(cnt, cal(r2-l1, k, i)+i*d); //枚举取最小值
printf("%lld\n", cnt);
}
}
return ;
}
signed main(){
cf();
return 0;
}