7-26课程解析+总结
题目解析+总结
T637650
给定一个数字,请求出这个数的每个位数上的值最小是多少。
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int x,y = 10; //y表示这个数的每个位数上的最小值
cin>>x;
while(x){
y = min(y,x%10); //截取位数
x /= 10;
}
if(y != 10) cout<<y<<endl; //加入特判
else cout<<0<<endl;
return 0;
}总结
使用模法和打擂台。
T637652
给定一个长度为的数组(),要截取一个长度为的连续的数组且不能有并且两个连续的截取中间必须有或,请问能截取多少个满足以上条件的数组。
分析
输入时开始求前缀和,统计出现的个数。
cin>>a[i];
s[i] = s[i-1] + a[i];然后定义一个变量,表示天数,放到while循环里面。 当两个数中没有出现时(也就是第个点的前缀和减第个点的前缀和,且不是),统计个数并更新。
int day = 1,cnt = 0;
while(day+k-1 <= n){
if(s[day+k-1]-s[day] == 0 && a[day] != 1) cnt++,day += k+1;
else day++;
}代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,k,a[100005],s[100005];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n>>k;
for(int i=1;i<=n;++i){
cin>>a[i];
s[i] = s[i-1] + a[i];
}
int day = 1,cnt = 0;
while(day+k-1 <= n){
if(s[day+k-1]-s[day] == 0 && a[day] != 1) cnt++,day += k+1;
else day++;
}
cout<<cnt<<endl;
return 0;
}总结
模拟法 + 前缀和
T637845
有个数字,每个数字为,你在第个点上。再给定一个危险数值,初始为。每过一秒,危险数值会增加。如果你位置上的数字严格小于危险数值,你因为你的位置爆炸,最终GG。 你有一个瞬移功能,从传送到,需花费秒,过去秒,你的瞬移功能才会生效。请问,在不GG的情况下,是否可以到达数字的最高处?
分析
在不要GG的情况下,需要移动到比这个位置对应的数值大的位置,移动时间为数值的差。时间结束,才能真正的瞬移过去。 样例:
5 1
2 3 5 7 9方案一,直接移到终点。 1 -> 5,需要秒,但是到了第秒,这个位置就炸了,GG 1 -> 2 -> 3 -> 4 -> 5,需要秒,但是可以到达终点。 最优策略:每次瞬移到与这个数字大且相近的。前提是需要排序。
int id = a[k],water = 1;
sort(a+1,a+1+n);
bool lose = 0;
for(int i=1;i<=n;++i){
if(a[i] <= id) continue;
int time = a[i] - id;
if(water+time-1 > id){
cout<<"NO\n";
lose = 1;
break;
}
water += time;
id = a[i];
}
if(!lose) cout<<"YES\n";代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int a[100005],b[100005];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int t; cin>>t;
while(t--){
int n,k;
cin>>n>>k;
for(int i=1;i<=n;++i) cin>>a[i];
int id = a[k],water = 1;
sort(a+1,a+1+n);
bool lose = 0;
for(int i=1;i<=n;++i){
if(a[i] <= id) continue;
int time = a[i] - id;
if(water+time-1 > id){
cout<<"NO\n";
lose = 1;
break;
}
water += time;
id = a[i];
}
if(!lose) cout<<"YES\n";
}
return 0;
}总结
模拟法 + 贪心
T637434
给定一个长度为的数组,你要对进行若干次操作:
- 选择两个数字,,把改成
- 任取三个数,,,都有
- 重复第一个步骤
输出最少操作次数
分析
暴力:先排序,然后枚举最小的两条边,比最小的那个边,还小的数字一定要修改,然后检查后面的数字,如果不满足,修改。
for(int i=1;i<n;++i){
int cnt = i-1;
for(int j=i+2;j<=n;++j){
if(check(a[i],a[i+1],a[j])) cnt++;
}
minn = min(minn,cnt);
}暴力:先排序,然后枚举最小的两条边,比最小的那个边,还小的数字一定要修改,然后直接找不满足的下标,修改。
int cnt = i-1;
int pos = lower_bound(a+1,a+1+n,a[i]+a[i+1])-a;
cnt += n-pos+1;
minn = min(minn,cnt);代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,a[100005];
signed 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+1+n);
int minn = 1e18;
for(int i=1;i<n;++i){
int cnt = i-1;
int pos = lower_bound(a+1,a+1+n,a[i]+a[i+1])-a;
cnt += n-pos+1;
minn = min(minn,cnt);
}
cout<<minn<<endl;
}
return 0;
}总结
二分法 + 排序解决各种难题