Codeforces Round #286 (Div. 2) A - Mr. Kitayuta's Gift ( 暴力枚举)std:string::insert

来源:互联网 发布:上海回力鞋淘宝网 编辑:程序博客网 时间:2024/06/05 07:59

题目连接:  http://codeforces.com/contest/505/problem/A

在比赛时硬是觉得有其他方法,于是想新方法想了半天,都没结果。最后还是老老实实的写暴力枚举。

#include <bits/stdc++.h>using namespace std;int len;void change(char *s , char *ans , int index){     if(index == len)     {          ans[len] = ans[0];     }     for(int i = 0 , j = 0 ; i < len ; i++)     {          if(i == index)          {               ans[j++] = ' ';               ans[j++] = s[i];          }          else               ans[j++] = s[i];     }}bool check(char *ans){     for(int i = 0 , j = len; i < j; )     {          if(ans[i] == ' ')               ans[i++] = ans[j--];          else if (ans[j] == ' ')               ans[j--] = ans[i++];          else if(ans[j] == ' ' && ans[i] == ' ')               ans[i] = 'a';          else if(ans[i++] != ans[j--])               return false;     }     return true;}int main(){     char s[12] , ans[12];     cin >> s ;     len = strlen(s);     ans[len + 1] = s[len];     for(int i = 0 ; i <= len ; i++)     {          change(s,ans,i);          if(check(ans))          {               cout << ans << endl;               return 0;          }     }     cout << "NA" <<endl;     return 0;}

在学了别人的代码之后才知道string有insert方法可以很方便的解决此题

直接枚举各个位置、各个位置上的26种情况

附上代码、这代码写的就很方便

//code copy from  elvina ,thanks elvina #include <bits/stdc++.h>using namespace std;char s[20], tab[20];int n;bool pali(){for (int i=0;i<=n;i++)if (tab[i] != tab[n-i]) return 0;return 1;}int main(){scanf("%s",s);n = strlen(s);for (int x=0;x<=n;x++){for (int i=0;i<x;i++) tab[i] = s[i];for (int i=x+1;i<=n;i++) tab[i] = s[i-1];for (int i='a';i<='z';i++){tab[x] = i;if (pali()){printf("%s",tab);return 0;}}}printf("NA");}


也通过这题我学习了insert,以下insert的用法供大家参考

// inserting into a string#include <iostream>#include <string>int main (){  std::string str="to be question";  std::string str2="the ";  std::string str3="or not to be";  std::string::iterator it;  // used in the same order as described above:  str.insert(6,str2);                 // to be (the )question  str.insert(6,str3,3,4);             // to be (not )the question  str.insert(10,"that is cool",8);    // to be not (that is )the question  str.insert(10,"to be ");            // to be not (to be )that is the question  str.insert(15,1,':');               // to be not to be(:) that is the question  it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question  str.insert (str.end(),3,'.');       // to be, not to be: that is the question(...)  str.insert (it+2,str3.begin(),str3.begin()+3); // (or )  std::cout << str << '\n';  return 0;}



1 0
原创粉丝点击