Title

UVA13181 Sleeping in hostels 题解

题目大意

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

解题思路

分两种情况讨论:

  1. 只有一个 X,那么答案为这个 X 到开头和结尾的最小距离,即 min$(pos_x-pos1-1,pos_{len}-pos_x-1)$。
  2. 有多个 X 那么我们尽量取两个 X 间的中间位置,此时的最小距离为 $\frac{(x_i-x_{i-1}-2)}{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 @ 2023-10-09 15:18  UncleSam_Died  阅读(20)  评论(0)    收藏  举报  来源