20250901 Codeforces 1555B
Codeforces 1555B
题目链接:https://codeforces.com/contest/1555/problem/B
You have an axis-aligned rectangle room with width \(W\) and height \(H\), so the lower left corner is in point \((0, 0)\) and the upper right corner is in \((W, H)\).
There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in \((x_1, y_1)\), and the upper right corner in \((x_2, y_2)\).
You want to place another rectangular table in this room with width \(w\) and height \(h\) with the width of the table parallel to the width of the room.
The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).
You can't rotate any of the tables, but you can move the first table inside the room.
Example of how you may move the first table.
What is the minimum distance you should move the first table to free enough space for the second one?
题目标签:贪心、模拟.
我们规定:如果两个长方形可以位于一条水平线的两侧,那么我们认为这两个长方形是上下关系;如果两个长方形可以位于一条垂直线的两侧,那么我们认为这两个长方形是左右关系
显然,如果两个长方形不相交,那么他们至少具有上述两种关系的一种。
考虑贪心。因为只需要拥有一种关系就可以满足题意。那么我们就考虑具有哪一种关系即可;换言之,只要让第一张桌子水平移动或者垂直移动即可。这显然是最优的。
如果具有上下关系,那么整个房间必须得能够容纳两个桌子。也就有$$W >= w + (x2 - x1)$$然后去模拟移动的过程。
如果是把第一个桌子往右移,也就是说要让第一个桌子左侧空出w的距离,因为第一个桌子距离左边墙x1的距离,那么这个时候的最小距离是max(0, w - x1)。
如果是把第一个桌子往左移,也就是说第一个桌子右侧空出w的距离;因为第一个桌子距离右侧墙W - x2的距离,那么这个时候的最小距离是max(0, w - (W - x2))
上下移动的情况同理。
考虑锦标赛,不断让ans取min就可以了。
#include <bits/stdc++.h>
using u32 = uint32_t;
using i64 = int64_t;
using u64 = uint64_t;
using i128 = __int128;
using u128 = unsigned __int128;
using namespace std;
#define F(i, a, b) for (int i = (a); i <= (b); i++)
#define Fd(i, a, b) for (int i = (a); i >= (b); i--)
#ifndef DEBUG
struct __X {
__X& operator<<(const auto& str) { return *this; }
void sp(const std::string& str = "") {}
} dout;
#define debug(x) ;
#endif
constexpr int mod = 998244353;
constexpr int MOD = 1E9 + 7;
constexpr int INF = 1E9;
constexpr int N = 2E5 + 10;
void sol() {
int W, H, w, h, x1, x2, y1, y2;
cin >> W >> H >> x1 >> y1 >> x2 >> y2 >> w >> h;
int ans = INT_MAX;
if (W >= x2 - x1 + w) {
ans = min(ans, max(0, x2 - (W - w)));
ans = min(ans, max(0, w - x1));
}
if (H >= y2 - y1 + h) {
ans = min(ans, max(0, y2 - (H - h)));
ans = min(ans, max(0, h - y1));
}
cout << (ans == INT_MAX ? -1 : ans) << '\n';
}
signed main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int T;
cin >> T;
while (T --) sol();
}
/* By Tangzy
⠄⠄⠄⠄⢠⣿⣿⣿⣿⣿⢻⣿⣿⣿⣿⣿⣿⣿⣿⣯⢻⣿⣿⣿⣿⣆⠄⠄⠄
⠄⠄⣼⢀⣿⣿⣿⣿⣏⡏⠄⠹⣿⣿⣿⣿⣿⣿⣿⣿⣧⢻⣿⣿⣿⣿⡆⠄⠄
⠄⠄⡟⣼⣿⣿⣿⣿⣿⠄⠄⠄⠈⠻⣿⣿⣿⣿⣿⣿⣿⣇⢻⣿⣿⣿⣿⠄⠄
⠄⢰⠃⣿⣿⠿⣿⣿⣿⠄⠄⠄⠄⠄⠄⠙⠿⣿⣿⣿⣿⣿⠄⢿⣿⣿⣿⡄⠄
⠄⢸⢠⣿⣿⣧⡙⣿⣿⡆⠄⠄⠄⠄⠄⠄⠄⠈⠛⢿⣿⣿⡇⠸⣿⡿⣸⡇⠄
⠄⠈⡆⣿⣿⣿⣿⣦⡙⠳⠄⠄⠄⠄⠄⠄⢀⣠⣤⣀⣈⠙⠃⠄⠿⢇⣿⡇⠄
⠄⠄⡇⢿⣿⣿⣿⣿⡇⠄⠄⠄⠄⠄⣠⣶⣿⣿⣿⣿⣿⣿⣷⣆⡀⣼⣿⡇⠄
⠄⠄⢹⡘⣿⣿⣿⢿⣷⡀⠄⢀⣴⣾⣟⠉⠉⠉⠉⣽⣿⣿⣿⣿⠇⢹⣿⠃⠄
⠄⠄⠄⢷⡘⢿⣿⣎⢻⣷⠰⣿⣿⣿⣿⣦⣀⣀⣴⣿⣿⣿⠟⢫⡾⢸⡟⠄.
⠄⠄⠄⠄⠻⣦⡙⠿⣧⠙⢷⠙⠻⠿⢿⡿⠿⠿⠛⠋⠉⠄⠂⠘⠁⠞⠄⠄⠄
⠄⠄⠄⠄⠄⠈⠙⠑⣠⣤⣴⡖⠄⠿⣋⣉⣉⡁⠄⢾⣦⠄⠄⠄⠄⠄⠄⠄⠄
*/

浙公网安备 33010602011771号