POJ 2038

#include <iostream> #include <string> #define F(i,a,b) for (int i = a; i<=b;i++) using namespace std; bool mk[6]; string a[102], ans; int _min = 0x7fffffff, n, b[6], c[6], map[ 128]; int mergesort(int l, int r) { int ret=0, total = 0; if (l<r) { int mid=(l+r)/2; ret=mergesort(l, mid) + mergesort(mid+1, r); int i=l, j=mid+1; int total=l; while(i<=mid || j<=r) { if (j>r || (i<=mid && b[i]<=b[j]) ) c[total++]=b[i++]; else { c[total++]=b[j++]; ret+=mid-i+1; } } F(i,l,r) b[i]=c[i]; } return ret; } int median( string s1, string s2) { F(i,0,4) map[ s1[i] ] = i; F(i,0, 4) b[i] = map[ s2[i] ]; return mergesort(0, 4 ); } void dfs( int x, string str) { if ( x == 6 ) { int sum = 0; for (int i = 1; i <=n && sum < _min; i++) sum += median( str, a[i] ); if ( sum < _min) { _min = sum; ans = str; } } else { F(i,0, 4 ) { if (!mk[i]) { mk[i] = true; dfs( x+1, str + (char)(65+i) ); mk[i] = false; } } } } int main() { while ( cin >> n && n != 0 ) { _min = 0x7fffffff; F(i,1,n) cin >> a[i] ; dfs(1, ""); printf( "%s is the median ranking with value %d./n", ans.c_str(), _min); } return 0; }

你可能感兴趣的:(c,String,BI,include)