div1 250pt
题意:一个长度最多50的字符串,每次操作可以交换相邻的两个字符,问,经过最多MaxSwaps次交换之后,最多能让多少个相同的字符连起来
解法:对于每种字符,枚举一个“集结点”,让其他相同的字符尽可能和它连起来。
1 // BEGIN CUT HERE 2 3 // END CUT HERE 4 #line 5 "ColorfulChocolates.cpp" 5 #include<cstdio> 6 #include<cstring> 7 #include<cstdlib> 8 #include<ctime> 9 #include<cmath> 10 #include<cassert> 11 #include<iostream> 12 #include<string> 13 #include<sstream> 14 #include<vector> 15 #include<map> 16 #include<set> 17 #include<queue> 18 #include<stack> 19 #include<algorithm> 20 using namespace std; 21 typedef long long ll; 22 typedef pair<int,int> pii; 23 class ColorfulChocolates 24 { 25 public: 26 int maximumSpread(string chocolates, int maxSwaps){ 27 //$CARETPOSITION$ 28 int n=chocolates.size(),answer = 0; 29 for(int i=0;i<n;i++){ 30 char c = chocolates[i]; 31 vector<int> tmp;int have = 1; 32 for(int j=i-1;j>=0;j--){ 33 if(chocolates[j]==c){ 34 tmp.push_back(i-j-have);have++; 35 } 36 } 37 have = 1; 38 for(int j=i+1;j<n;j++){ 39 if(chocolates[j]==c){ 40 tmp.push_back(j-i-have);have++; 41 } 42 } 43 sort(tmp.begin(),tmp.end()); 44 int res = maxSwaps,total = 1; 45 for(int j=0;j<tmp.size();j++){ 46 if(res >= tmp[j]){ 47 ++total;res-=tmp[j]; 48 }else break; 49 } 50 answer = max(answer,total); 51 } 52 return answer; 53 54 55 } 56 57 // BEGIN CUT HERE 58 public: 59 void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } 60 private: 61 template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } 62 void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } 63 void test_case_0() { string Arg0 = "ABCDCBC"; int Arg1 = 1; int Arg2 = 2; verify_case(0, Arg2, maximumSpread(Arg0, Arg1)); } 64 void test_case_1() { string Arg0 = "ABCDCBC"; int Arg1 = 2; int Arg2 = 3; verify_case(1, Arg2, maximumSpread(Arg0, Arg1)); } 65 void test_case_2() { string Arg0 = "ABBABABBA"; int Arg1 = 3; int Arg2 = 4; verify_case(2, Arg2, maximumSpread(Arg0, Arg1)); } 66 void test_case_3() { string Arg0 = "ABBABABBA"; int Arg1 = 4; int Arg2 = 5; verify_case(3, Arg2, maximumSpread(Arg0, Arg1)); } 67 void test_case_4() { string Arg0 = "QASOKZNHWNFODOQNHGQKGLIHTPJUVGKLHFZTGPDCEKSJYIWFOO"; int Arg1 = 77; int Arg2 = 5; verify_case(4, Arg2, maximumSpread(Arg0, Arg1)); } 68 69 // END CUT HERE 70 71 }; 72 // BEGIN CUT HERE 73 int main(){ 74 ColorfulChocolates ___test; 75 ___test.run_test(-1); 76 return 0; 77 } 78 // END CUT HERE