Guest User

Untitled

a guest
Jul 15th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3.  
  4. #define NMAX 2000
  5. char bits[NMAX];
  6.  
  7. void solve(void)
  8. {
  9. FILE *fin, *fout;
  10. int N, swaps = 0, i, j;
  11.  
  12. fin = fopen("swaps2.in", "rt");
  13. fout = fopen("swaps2.out", "w+");
  14.  
  15. fscanf(fin, "%d ", &N);
  16.  
  17. // N should be equal with strlen(bits);
  18. for (i = 0; i < N; i++)
  19. fscanf(fin, "%c", &bits[i]);
  20. //forward writing, just to hold space for first line
  21. //we'll be back to this when swaps will be known
  22. fprintf(fout, "%d\n", swaps);
  23. i = 0; j = N - 1;
  24. //walk the array from both ends, check and count swaps
  25. // i -> .... <- j
  26. while (i < j) {
  27. if (bits[i] == '0') {
  28. i++;
  29. continue;
  30. }
  31. if (bits[j]=='1') {
  32. j--;
  33. continue;
  34. }
  35. //at this point we must simulate swap between i <-> j
  36. fprintf(fout, "%d %d\n", i+1, j+1);
  37. swaps++;
  38. i++; j--;
  39. }
  40.  
  41. //go back and write the actual number of swaps
  42. fseek(fout, 0, SEEK_SET);
  43. fprintf(fout, "%d\n", swaps);
  44.  
  45. }
  46.  
  47.  
  48. int main(void)
  49. {
  50. solve();
  51.  
  52. return 0;
  53. }
Add Comment
Please, Sign In to add comment