Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #define NMAX 2000
- char bits[NMAX];
- void solve(void)
- {
- FILE *fin, *fout;
- int N, swaps = 0, i, j;
- fin = fopen("swaps2.in", "rt");
- fout = fopen("swaps2.out", "w+");
- fscanf(fin, "%d ", &N);
- // N should be equal with strlen(bits);
- for (i = 0; i < N; i++)
- fscanf(fin, "%c", &bits[i]);
- //forward writing, just to hold space for first line
- //we'll be back to this when swaps will be known
- fprintf(fout, "%d\n", swaps);
- i = 0; j = N - 1;
- //walk the array from both ends, check and count swaps
- // i -> .... <- j
- while (i < j) {
- if (bits[i] == '0') {
- i++;
- continue;
- }
- if (bits[j]=='1') {
- j--;
- continue;
- }
- //at this point we must simulate swap between i <-> j
- fprintf(fout, "%d %d\n", i+1, j+1);
- swaps++;
- i++; j--;
- }
- //go back and write the actual number of swaps
- fseek(fout, 0, SEEK_SET);
- fprintf(fout, "%d\n", swaps);
- }
- int main(void)
- {
- solve();
- return 0;
- }
Add Comment
Please, Sign In to add comment