2025.07.26课堂总结
闲话
今天又烤翅了,lldq终于没有再为难我们的第一题。太豪了!
T637845 快往上爬
这道题我一开始就用dfs去写,但是因为我赶时间所以我用三十分钟左右的时间去写,写出了这坨大的:
#include<bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;
const int N = 1e5 + 5;
bool f, vis[N];
int n, k, wath = 1;
ll h[N], maxx;
void dfs(int t){
if(h[t] == maxx){
cout << "YES" <<endl;
f = 1;
return ;
}
for(int i = 1; i <= n; i++){
if(i == t) continue;
if(abs(h[t] - h[i]) > h[k] && vis[i] == 0){
vis[i] = 1;
wath += abs(h[t] - h[i]);
dfs(i);
}
}
}
int main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int T;
cin >> T;
while(T--){
cin >> n >> k;
for(int i = 1; i <= n; i++){
cin >> h[i];
maxx = max(maxx, h[i]);
}
if(k == maxx){
cout << "YES"<<endl;
continue;
}
vis[k] = 1;
dfs(k);
if(f == 0) cout << "NO" <<endl;
for(int i = 1; i <= n; i++) h[i] = vis[i] = 0;
f = 0;
maxx = 0;
}
return 0;
}我的代码存在的问题是:
- dfs判断条件写错,传送可行性不取决于初始塔的高度;
- 水位跟踪出现错误,未写wath的回溯
- 未处理最大高度塔的多个出现
- 变量 f、vis、h 和 maxx 在测试用例间未完全重置 所以,我没用贪心的方法,照着重新改了一遍:
#include<bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;
const int N = 1e5 + 5;
bool f, vis[N];
int n, k, wath = 1, hh;
ll h[N], maxx;
void dfs(int t, int x){//t代表位置,x代表高度,hh为水高度
if(x >= maxx){
f = 1;
return ;
}
for(int i = 1; i <= n; i++){
if(hh + abs(h[t] - h[i]) <= x && vis[i] == 0 && h[i] > h[t]){//判断条件修改
vis[i] = 1;
hh += abs(h[t] - h[i]);
dfs(i, h[i]);
vis[0];
}
}
return ;
}
int main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int T;
cin >> T;
while(T--){
cin >> n >> k;
for(int i = 1; i <= n; i++){
cin >> h[i];
maxx = max(maxx, h[i]);
}
vis[k] = 1;
dfs(k, h[k]);
cout << (f == 1 ? "YES" : "NO") <<endl;//任意最高塔即可
for(int i = 1; i <= n; i++) h[i] = vis[i] = 0;//清空修改
f = 0;
hh = 0;
maxx = 0;
}
return 0;
}T637434 小梦分糖果
这题从头到尾我都是以暴力的方式写的能得十分已经是奇迹了。核心点在于枚举区间。 代码+注释如下:
#include<bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;
const int N = 1e5 + 5;
int n, ans;
ll a[N], maxx;
int main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int T;
cin >> T;
while(T--){
cin >> n;
for(int i = 1; i <= n; i++) cin >> a[i];
sort(a + 1, a + n + 1); // 排序
ans = INT_MAX;
// 枚举每个位置i(从1到n-1)
for(int i = 1; i < n; i++){
// cnt计算需要修改的操作次数
int cnt = i - 1; // 区间[1, i-1]的数都需要修改(共i-1个)
// 寻找
int pos = lower_bound(a + 1, a + n + 1, a[i] + a[i+1]) - a;
cnt += n - pos + 1;
// 更新最小操作次数
ans = min(ans, cnt);
}
cout << ans << endl;
}
return 0;
}