Title

UVA13181 Sleeping in hostels 题解

题目大意

有若干组读入,每次告诉你一个由 X. 组成的字符串 s,请你找到一个位置,使得这个地方到离它最近的 X 的距离最小。

解题思路

分两种情况讨论:

  1. 只有一个 X,那么答案为这个 X 到开头和结尾的最小距离,即 min(posxpos11,poslenposx1)
  2. 有多个 X 那么我们尽量取两个 X 间的中间位置,此时的最小距离为 (xixi12)2

时间复杂度为 O(n)

AC 代码

#include<bits/stdc++.h>
#define ll long long
#define ull usigned long long
using namespace std;
const string TypideName="c";
inline void readc(char &c){
    c=getchar();
    while(c==' '||c=='\n')
        c=getchar();
}inline void writec(char c){putchar(c);}
template<typename T>inline void read(T& x) {
    if(typeid(x).name()==TypideName){char ch;readc(ch);x=ch;return;}
    x = 0; bool f = false; char ch = getchar();
    while (ch < '0' || ch>'9') { if (ch == '-') f = !f; ch = getchar(); }
    while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); }
    x = (f ? -x : x); return;
}template<typename T>inline void put(T x) {
    if (x < 0) putchar('-'), x = -x;
    if (x > 9) put(x / 10);
    putchar(x % 10 + '0'); return;
}template<typename T>inline void write(T x) {
    if(typeid(x).name()==TypideName){writec(x);return;}
    put(x);
}
template<typename T,typename... Args>
inline void read(T& x,Args&...x_) {read(x),read(x_...);}
template<typename T,typename... Args>
inline void write(T x,Args...x_){write(x),write(x_...);}
string s;
#define N 500005
int pos[N],ce;
inline void work(){
    int len=s.length();ce=0;
    for(int i=0;i<len;i++)
        if(s[i]=='X') 
            pos[++ce]=i;
    if(ce==1){
        write(max(pos[1]-1,len-pos[1]-2),'\n');
        return;
    }
//  for(int i=1;i<=ce;i++)
//      write(pos[i],' ');write('\n');
    int ans=max(pos[1]-1,len-pos[ce]-2);
    for(int i=2;i<=ce;i++){
        ans=max(ans,(pos[i]-pos[i-1]-2)/2);
    }write(ans,'\n');
}
signed main(){
    while(cin>>s) work();
    return 0;
}
posted @   UncleSam_Died  阅读(3)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示