Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
受不了了,用merge实现的O(nlgn)的,打印出来结果正确的,为啥就是通不过求指点啊~~~~ #include<stdio.h> #include<iostream> using namespace std; int merge(char *line, int first, int mid, int last) { int i = first; int j = mid + 1; char * temp = new char[last-first+1+1]; temp[last-first+1] = '\0'; int index = 0; int ret = 0; while(i <=mid && j<= last) { if(line[i] <= line[j]) { temp[index] = line[i]; index++; i++; } else { temp[index] = line[j]; ret = ret + mid - i + 1; index++; j++; } } if(i != mid + 1) { temp[index] = line[i]; index++; i++; } while(i != mid +1) { temp[index] = line[i]; ret = ret + last - mid; index++; i++; } while(j != last + 1) { temp[index] = line[j]; index++; j++; } j = 0; for(i = first; i<= last; i++) { line[i] = temp[j]; j++; } return ret; } int getInversions(char *line, int first, int last) { if(last == first) { return 0; } int mid = (last+first)/2; int a = getInversions(line, first, mid); int b = getInversions(line, mid+1, last); int c = merge(line, first, mid, last); return a+b+c; } void solve(char **p, int *inversions, int m, int n) { int i = 0; for(int i = 0; i < m; i++) { inversions[i] = getInversions(p[i], 0, n-1); } } int main() { int n, m; int i = 0; cin >> n >> m; char **p = new char*[m]; char **record = new char*[m]; int *inversions = new int[m]; bool *used = new bool[m]; for(i = 0; i< m; i++) { p[i] = new char[n+1]; record[i] = new char[n+1]; cin >> p[i]; strcpy(record[i], p[i]); } solve(p, inversions, m, n); for(i = 0; i< m; i++) { used[i] = false; } int min; int keep; int count = m; while(count > 0) { for(i = 0 ;i < m; i++) { if(!used[i]) { min = inversions[i]; keep = i; break; } } for(;i < m; i++) { if(!used[i] && inversions[i] < min) { min = inversions[i]; keep = i; } } cout << record[keep] << endl; used[keep] = true; count--; } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator