好吧。。这题实在是不想用C写了,本来计算两个串的distance value函数都用C写好了,求全排列没有list用怎么想怎么麻烦,还是JAVA用起来顺手。。几下就搞定了
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
ArrayList<String> src = perm("ABCDE");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
while (n != 0)
{
ArrayList<String> input = new ArrayList<String>();
for (int i = 0; i < n; i++)
input.add(sc.nextLine());
int min = Integer.MAX_VALUE;
String result = null;
for (String s : src)
{
int sum = 0;
for (String ins : input)
sum += rankValue(s, ins);
if (sum < min)
{
min = sum;
result = s;
}
}
System.out.format("%s is the median ranking with value %d.\n",
result, min);
n = sc.nextInt();
sc.nextLine();
}
}
static int rankValue(String ss1, String ss2)
{
char[] s1 = ss1.toCharArray();
char[] s2 = ss2.toCharArray();
int[] index = new int[5];
int i, j, count = 0;
for (i = 0; i < 5; i++)
index[s2[i] - 'A'] = i;
for (i = 0; i < 4; i++)
for (j = i + 1; j < 5; j++)
if (index[s1[i] - 'A'] - index[s1[j] - 'A'] > 0)
count++;
return count;
}
static ArrayList<String> perm(String s)
{
ArrayList<String> res = new ArrayList<String>();
if (s.length() == 2)
{
res.add(s);
res.add(s.charAt(1) + "" + s.charAt(0));
}
else
{
for (char c : s.toCharArray())
{
ArrayList<String> temp = perm(removeChar(s, c));
for (String ss : temp)
res.add(c + ss);
}
}
return res;
}
static String removeChar(String s, char c)
{
StringBuilder sb = new StringBuilder();
for (char cc : s.toCharArray())
if (cc != c)
sb.append(cc);
return sb.toString();
}
}