给一个整型数组编号b.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include <stdio.h>
  2. #include <stdlib.h> // Include stdlib.h for qsort function
  3. typedef struct {
  4. int value;
  5. int originalIndex;
  6. } Element;
  7. // Compare function for sorting elements in descending order
  8. int compare(const void *a, const void *b) {
  9. Element *elem1 = (Element *)a;
  10. Element *elem2 = (Element *)b;
  11. return elem2->value - elem1->value; // Sort in descending order
  12. }
  13. int main() {
  14. int n; // Number of elements in the array
  15. scanf("%d", &n);
  16. Element arr[n]; // Array of elements with original indices
  17. // Read elements and store them with their original indices
  18. int i;
  19. for (i = 0; i < n; ++i) {
  20. scanf("%d", &arr[i].value);
  21. arr[i].originalIndex = i;
  22. }
  23. // Sort elements in descending order based on value
  24. qsort(arr, n, sizeof(Element), compare); // Use qsort from stdlib.h
  25. // Array to store the ranks
  26. int ranks[n];
  27. // Assign ranks
  28. ranks[arr[0].originalIndex] = 1; // Start with rank 1 for the largest element
  29. for (i = 1; i < n; ++i) {
  30. if (arr[i].value == arr[i - 1].value) {
  31. ranks[arr[i].originalIndex] = ranks[arr[i - 1].originalIndex];
  32. } else {
  33. ranks[arr[i].originalIndex] = i + 1; // Assign next rank
  34. }
  35. }
  36. // Output the ranks in the original order
  37. for (i = 0; i < n; ++i) {
  38. printf("%d", ranks[i]);
  39. if (i < n - 1) {
  40. printf(" ");
  41. }
  42. }
  43. printf("\n");
  44. return 0;
  45. }