B. Vova and Trophies
阿新 • • 發佈:2018-11-30
連結
[https://codeforces.com/contest/1082/problem/B]
題意
給你一個包含GS的字串,只允許交換一次任意不同位置的字元,問最長的連續G串是多少
分析
很顯然貪心找相鄰的中間間隔一個S的兩個連續G串
看了別人寫的很巧妙,多用幾個樣例就知道其中的奧妙了
程式碼
#include<bits/stdc++.h> using namespace std; int main(){ int n; string s; //freopen("in.txt","r",stdin); while(cin>>n){ cin>>s; int cntG=0,cntS=0,sumG=0,ans=0; for(int i=0;i<n;i++){ if(s[i]=='G'){ cntG++; sumG++; } else{ cntS=cntG; cntG=0;//遇到scntG從新歸零統計G連續的個數 } ans=max(ans,cntG+cntS+1);//假設都可以交換帶來收益 } ans=min(ans,sumG);//這裡很關鍵存在交換沒有帶來收益的 cout<<ans<<endl; } return 0; }