UVa:1610 Party Games(字串處理)
阿新 • • 發佈:2018-12-13
題意:
給出n個串(n為偶數);
要構造一個串,使n串中有一半小於等於它,另外一半大於它;
要求這個串長度儘量小,同時字典序小
思路1:得益於string自帶字典序比較,所以先對整個字串組排序,那麼中間兩個a,b,答案就要滿足大於等於a,小於b,因為有些細節問題的存在,所以直接暴力列舉就行了
#include <iostream> #include <cstdio> #include <bitset> #include <cstring> #include <algorithm> #include <vector> #include <map> #include <cmath> #include <set> #include <queue> using namespace std; typedef long long ll; const int INF=1e9+100; const int mod=1e9+7; string s[1005],a,b,ans; void dfs(int pos,string tmp){ if(tmp>=b) return; if(tmp>=a&&tmp<b){ if(ans=="") ans=tmp; else{ if(ans.length()>tmp.length()) ans=tmp; } return; } char c=a[pos]; if(pos>=a.length()) c='A'; for(;c<='Z';c++){ dfs(pos+1,tmp+c); } } int main(){ //freopen("out.txt","w",stdout); int n; while(cin>>n){ if(n==0) break; for(int i=0;i<n;i++) cin>>s[i]; sort(s,s+n); flag=0; ans=""; a=s[n/2-1];b=s[n/2]; dfs(0,""); cout<<ans<<endl; } return 0; }
思路2:考慮各種情況,非常難
#include <cstdio> #include <cstring> #include <vector> #include <queue> #include <stack> #include <sstream> #include <algorithm> #include <iostream> using namespace std; int main() { int n,t; string str,s1,s2,sres,tmp; vector<string> vstr; while(scanf("%d", &n)&&n) { t=n; vstr.clear(); while(t--) { cin>>str; vstr.push_back(str); }; sort(vstr.begin(),vstr.end()); s1=vstr[n/2-1]; s2=vstr[n/2]; int s1_len=s1.length(); int s2_len=s2.length(); sres=""; int minl=min(s1_len,s2_len); for (int i = 0; i < minl; ++i) if (s1[i] == s2[i]) sres += s1[i]; else { tmp = sres + (char)(s1[i] + 1); if (tmp == s2) { sres+= s1[i++]; while (i < s1_len - 1 && s1[i] == 'Z') sres += s1[i++]; if (i < s1_len - 1) sres += (char)(s1[i] + 1); else sres = s1; } else { if (tmp.size() == s1_len) sres= s1; else sres = tmp; } break; } cout<<sres<<endl; } return 0; }