题意
给定n个长方形,要将这n个长方形相连起来。要求
- 长方形直接不能相互重叠,但边可以相邻。
- 每个长方形,至少有一条边连接x轴。
- 可以选择长方形,但要保证长方形的每条边,要么与x轴平行,要么与y轴平行
求将这n个长方形相连,需要的最小外围。
思路
外围,即组成的大长方形的周长。
大长方形的周长,长为所有长方形的最大长;宽为所有长方形的宽的总和。
贪心,短的边与x轴平行,长的边与y轴平行。
证明:
- 对于长边y ==max(y)的长方形。它对整体的周长贡献是2x+2y。如果将它旋转90度,那么它的宽贡献增加2*(y-x),长的贡献最多减少2*(y-x)。这么一折腾,我们发现它其实不能减少总贡献。
- 对于长边y < max(y),最优策略显然是让短的边做为宽,与x轴相连。
代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pcc pair<char, char>
#define pii pair<int, int>
#define inf 0x3f3f3f3f
#define se second
#define fi first
const int maxn = 200010;
const int mod = 998244353;
int n;
int a, b;
void solve() {
scanf("%d", &n);
ll res = 0;
int mx = 0;
for (int i = 0; i < n; ++i) {
scanf("%d%d", &a, &b);
if (a > b) {
swap(a, b);
}
res += a;
mx = max(mx, b);
}
printf("%lld\n", (res + mx) * 2);
}
int main() {
int t = 1;
scanf("%d", &t);
int cas = 1;
while (t--) {
// printf("cas %d:\n", cas++);
solve();
}
}