10.30课程题目解析+总结
题目解析+总结
P9045 [PA 2021] Oranżada
分析题干+步骤书写
我们就是要保证最左边个饮料瓶种类不同,则说明要存在个不同的品牌。 第瓶饮料就是一个不同品牌的饮料,则只需保证~中的瓶子品牌都不相同。 我们只需用桶来统计每一个品牌的饮料第一次出现的位置,随后将它交换到里,计算出代价。
AC代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
map<int,int>vis;
int n,k,a[500005];
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];
int pos = 0,ans = 0;//记录代价数和放好的饮料瓶数量
for(int i=1;i<=n;++i){
if(pos >= k) break; //已经存好k瓶
if(!vis[a[i]]) pos++,ans += i-pos,vis[a[i]] = 1;
}
if(pos < k) cout<<-1<<endl;
else cout<<ans<<endl;
return 0;
}P1146 硬币翻转
分析题干+步骤书写
给定枚硬币正面朝上,我们每一次可以操作枚硬币。 为了让每枚硬币都背面朝上,我们需要操作奇数次,同样的操作不会再操作两遍。 设有枚硬币,则每一次操作都需要操作枚硬币。操作如下:
将操作结果变成01子串:
1 2 3 1110
1 2 4 1101
1 3 4 1011
2 3 4 0111我们可以发现,只要操作次,就可以将硬币变为全部硬币都是背面朝上。 若要考虑字典序,我们可以将操作形成的子串进行排序:
2 3 4 0111 一次不选1
1 3 4 1011 二次不选2
1 2 4 1101 三次不选3
1 2 3 1110 四次不选4后面只需将以上操作后的结果输出即可。
AC代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,a[105];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n;
cout<<n<<endl;
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
if(j != i) a[j] = !a[j]; //根据以上方法操作
cout<<a[j];
}
cout<<endl;
}
return 0;
}P1105 平台
分析题干+步骤书写
一共有个平台,高度为,左端点为,右端点为。 一个小球从平台上跳下去,想要掉在平台上,需要在 ~ 之间。 所以,只需暴力枚举每个平台即可。
AC代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n;
struct node{
int h,l,r;
}a[1005];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n;
for(int i=1;i<=n;++i) cin>>a[i].h>>a[i].l>>a[i].r;
for(int i=1;i<=n;++i){
int pre = 0,nex = 0,posl = a[i].l,posr = a[i].r;
for(int j=1;j<=n;++j){
if(a[j].h >= a[i].h) continue; //去掉不合理的情况
if(posl > a[j].l && posl < a[j].r){ //左端点掉落在第j个平台上,落下的位置必须在l_j+1 ~ r_j-1之间
if(a[pre].h < a[j].h) pre = j;
}
if(posr > a[j].l && posr < a[j].r){ //右端点掉落在第j个平台上,落下的位置必须在l_j+1 ~ r_j-1之间
if(a[nex].h < a[j].h) nex = j;
}
}
cout<<pre<<' '<<nex<<endl;
}
return 0;
}B4193 [海淀区小学组 2023] 排座位
分析题干+步骤书写
先计算出连续空着的座位数, 然后连续长度为的安排方式有且仅有两种:
- 男,女,男
- 女,男,女
然后计算每一段连续空位的长度。若长度为:
- 男生多,男生为,女生为;
- 女生多,男生为,女生为;
AC代码
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,a,b;
string s;
cin>>n>>a>>b>>s;
s = ' ' + s;
int cnt = 0,ans = 0;
for(int i=1;i<=n;++i){
if(s[i] == '.') cnt++; //计算连续空位数量
else{
if(a < b) swap(a,b);
int mina = min(a,cnt-cnt/2);
int minb = min(b,cnt/2);
a -= mina,b -= minb,ans += mina + minb,cnt = 0;
}
}
if(cnt > 0){ //若最终cnt不为0,再操作一次
// cout<<cnt<<endl;
if(a < b) swap(a,b);
int mina = min(a,cnt-cnt/2);
int minb = min(b,cnt/2);
a -= mina,b -= minb,ans += mina + minb;
}
cout<<ans<<endl;
return 0;
}