Input
There will be multiple input sets. Input for each set is a positive integer n on a line by itself, followed by n lines (n no more than 100), each containing a permutation of the letters A, B, C, D and E, left-justified with no spaces. The final input set is followed by a line containing a 0, indicating end of input.
Output
Output for each input set should be one line of the form:
ranking is the median ranking with value value.
Of course ranking should be replaced by the correct ranking and value with the correct value. If there is more than one median ranking, you should output the one which comes first alphabetically.
Sample Input
4
ABDCE
BACDE
ABCED
ACBDE
0
Sample Output
ABCDE is the median ranking with value 4.
代码实现:
do-while 与while的不同是do-while实现进行循环体一次然后再进行条件的判断,即不管怎样,do-while循环至少会执行一次循环体
// next_permutation(arr, arr+n)
// 返回的是bool值
#include<iostream>
#include<algorithm>
#include<map>
#include<cstring>
using namespace std;
map<char, int> m;
int countvalue(string temp) {
int sum = 0;
for (int i = 0; i < 4; ++i)
for (int j = i + 1; j < 5; ++j)
if (m[temp[i]] > m[temp[j]])
sum++;
return sum;
}
int main() {
int n;
while (cin >> n && n) {
string str = "ABCDE";
int count = 1000000000;
string *s = new string[n];
for (int i = 0; i < n; ++i)
cin >> s[i];
string temp;
do {
for (int i = 0; i < 5; ++i)
m[str[i]] = i;
int sum = 0;
for (int i = 0; i < n; ++i)
sum += countvalue(s[i]);
if (count > sum) {
count = sum;
temp = str;
}
} while (next_permutation(str.begin(), str.begin() + 5));
cout << temp << " is the median ranking with value " << count <<"."<< endl;
}
}