//AC Code #include <iostream> #define Swap(x,y) {int temp = x;x = y;y = temp;} #define MAX 50001 int map[MAX]; bool hash[MAX]; int main() { int i, j, k, n, v; while(scanf("%d%d", &n, &v) && n != -1) { memset(hash, false, sizeof(bool)*(n+1)); i = 2; while((i-1)*(i+2)/2 < v) i++; for(j = 1; j <= n-i-1;++j) { hash[j] = true; printf("%d ", j); } k = n-i-1 + v - (i-2)*(i+1)/2; printf("%d %d ", k, n); hash[k] = hash[n] = true; for(j = n; j >= n-i; --j) if(!hash[j]) printf("%d ", j); printf("/n"); } return 0; } //O(n) #include <iostream> #include <algorithm> using namespace std; #define MAX 50001 int map[MAX]; void print(int& v) { printf("%d ", v); } int calculate(int n) { int cnt = 0; for(int i = 1; i <= n-1; ++i) for(int j = i+1; j <= n; ++j) if(map[i] > map[j]) cnt++; return cnt; } int main() { int n, v; while(scanf("%d%d", &n, &v) && !(n == -1 && v == -1)) { for(int i = 1; i <= n; ++i) map[i] = i; while(next_permutation(map+1, map+n+1)) { if(calculate(n) == v) { for_each(map+1, map+n+1, print); printf("/n"); break; } } } return 0; } O(n^4) #include <iostream> #include <algorithm> using namespace std; #define MAX 50001 int map[MAX]; void next(int n) { int i; for(i = n; i >= 1 && map[i-1] > map[i]; i--) ; int low = i, high = n; while(low <= high) { int mid = (low+high) >> 1; if(map[mid] < map[i-1]) high = mid-1; else low = mid+1; } std::iter_swap(map+i-1, map+high); } int main() { int n, v; while(scanf("%d%d", &n, &v) && !(n == -1 && v == -1)) { for(int i = 1; i <= n; ++i) map[i] = i; for(int i = 1; i <= v; ++i) next(n); for(int i = 1; i <= n; ++i) printf("%d ", map[i]); printf("/n"); } return 0; } //O(n^2*logn) #include <stdio.h> #define Swap(x,y) {int temp = x;x = y;y = temp;} #define MAX 50001 int map[MAX]; int main() { int i, n, v; int x, y; while(scanf("%d%d", &n, &v) && n != -1) { for(i = 1; i <= n; ++i) map[i] = i; x = n-1, y = n; for(i = 1; i <= v; ++i) { if(x < y) { Swap(map[x],map[y]); y--; } else { x--; y = n; Swap(map[x], map[y]); y--; } } for(i = 1; i <= n; ++i) printf("%d ", map[i]); printf("/n"); } return 0; } //O(v) = O(n^2) result: 命中注定TLE