8.22总结

· · 科技·工程

T639114 大楼

简化题意

给定一个数组,如果有比第一个元素大的元素,输出其下标,否则输出 -1。

思路

1.模拟

  • 遍历数组,找到第一个比第一个元素大的元素,记录下标。
  • 如果找到,输出下标;否则输出 -1。

2.复杂度分析

  • 时间复杂度:O(n),其中 n 是数组的长度。
  • 空间复杂度:O(1)。

代码实现

#include<bits/stdc++.h>
using namespace std;
int n;
int main(){
    cin>>n;
    int ans,cnt=1;
    cin>>ans;
    n--;
    while(n--){
        int x;
        cin>>x;
        cnt++;
        if(x>ans){
            cout<<cnt;
            return 0;
        }
    }
    cout<<-1;
    return 0;
} 

U591726 盲打练习

简化题意

给定一个字符串 s 和一个字符串 t,判断 t 是否包含 s 的所有字符,并输出 t 中每个字符的下标。

思路

1. 模拟

  • 遍历字符串 t,对于每个字符,判断它是否在字符串 s 中出现。
  • 如果出现,则记录下标。
  • 最后输出所有记录的下标。

2. 复杂度分析

  • 时间复杂度:O(n),其中 n 是字符串 s 的长度。
  • 空间复杂度:O(1)。

代码实现

#include<bits/stdc++.h>
using namespace std;
string s,t;
int main(){
    cin>>s>>t;
    int cnt=0;
    for(int i=0;i<t.size()&&cnt<s.size();i++){
        if(t[i]==s[cnt]){
            cnt++;
            cout<<i+1<<' ';
        }
    }
    return 0;
} 

T657890 小 A 的口头禅

简化题意

给定一个字符数组,判断上下左右是否包含 "hehe" 这个字符串。

思路

1.模拟

  • 遍历字符数组,对于每个字符,判断其上下左右是否包含 "hehe" 这个字符串。
  • 如果包含,计数器加一。

2.复杂度分析

  • 时间复杂度:O(n^2),其中 n 是字符数组的大小。
  • 空间复杂度:O(1)。

代码实现

#include<bits/stdc++.h>
using namespace std;
int n,m;
char c[1010][1010];
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cin>>c[i][j];
        }
    }
    int cnt=0;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(j+4<=m+1){
                if(c[i][j]=='h'&&c[i][j+1]=='e'&&c[i][j+2]=='h'&&c[i][j+3]=='e') cnt++; 
            }
            if(j-4>=0){
                if(c[i][j]=='h'&&c[i][j-1]=='e'&&c[i][j-2]=='h'&&c[i][j-3]=='e') cnt++;
            }
            if(i+4<=n+1){
                if(c[i][j]=='h'&&c[i+1][j]=='e'&&c[i+2][j]=='h'&&c[i+3][j]=='e') cnt++;
            }
            if(i-4>=0){
                if(c[i][j]=='h'&&c[i-1][j]=='e'&&c[i-2][j]=='h'&&c[i-3][j]=='e') cnt++;
            }
        }
    }
    cout<<cnt;
    return 0;
} 

T638475 调酒大师

简化题意

给定一个正整数 n 和一个正整数 m,求 n 和 m 可以有多少种(n,m,n\m,n\m) 的搭配方案。

思路

1.模拟

  • 我们可以使用(dfs)来遍历所有可能的调酒方案。
  • 时间复杂度:O(2^n),其中 n 是调酒师的数量,会爆。

2.二分

  • 我们可以使用二分查找来优化调酒方案的选择。
  • 使用check函数来判断当前的调酒方案是否可行,如果剩余的酒水不足,则返回false。

3.复杂度分析

  • 时间复杂度:O(n \log m),其中 n 是调酒师的数量,m 是酒的种类。
  • 空间复杂度:O(1)。

代码实现

#include<bits/stdc++.h>
using namespace std;
int t; 
bool check(int x,int a,int b){
    if(a<x) return 0;
    if(b<x) return 0;
    if(a+b<x*4) return 0;
    return 1;
}
int main(){
    cin>>t;
    while(t--){
        int n,m;
        cin>>n>>m;
        int mid=0,l=0,r=max(n,m)+1;
        while(l+1<r){
            mid=r+l>>1;
            if(check(mid,n,m)){
                l=mid;
            }
            else{
                r=mid;
            }
        }
        cout<<l<<'\n';
    }
    return 0;
}