pb_jiang

gen.c

Jun 15th, 2023
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <assert.h>
  2. #include <stdio.h>
  3.  
  4. int cnt;
  5. int v[1000005];
  6.  
  7. int get_arr()
  8. {
  9.     FILE *pipe;
  10.  
  11.     // 打开另外一个程序并建立管道通信
  12.     pipe = popen("./gen2.py", "r");
  13.     if (pipe == NULL) {
  14.         fprintf(stderr, "无法打开程序\n");
  15.         return -1;
  16.     }
  17.  
  18.     // 读取程序的输出
  19.     fscanf(pipe, "%d", &cnt);
  20.     fprintf(stderr, "read cnt:%d from pipe\n", cnt);
  21.     int idx = 0;
  22.     while (fscanf(pipe, "%d", v + idx) != EOF) {
  23.         // printf("从程序2接收到的数据: %d\n", data);
  24.         idx++;
  25.     }
  26.     assert(idx == cnt);
  27.  
  28.     // 关闭管道通信
  29.     pclose(pipe);
  30.     return 0;
  31. }
  32.  
  33. int main(int argc, char **argv)
  34. {
  35.     assert(get_arr() == 0);
  36.     fprintf(stderr, "get %d elements from random\n", cnt);
  37.     int idx = 0, opt = 0;
  38.     printf("%d\n", v[idx]), fflush(stdout);
  39.     while (opt < 1000) {
  40.         char op;
  41.         int num;
  42.         scanf("%c%d", &op, &num);
  43.         if (op == '!') {
  44.             if (num == cnt) {
  45.                 fprintf(stderr, "bingo! %d\n", num);
  46.                 return 0;
  47.             } else {
  48.                 fprintf(stderr, "expect: %d, get: %d\n", cnt, num);
  49.                 return -1;
  50.             }
  51.         } else {
  52.             if (op == '+') {
  53.                 idx = (idx + num) % cnt;
  54.                 printf("%d\n", v[idx]), fflush(stdout);
  55.             } else if (op == '-') {
  56.                 idx = ((idx - num) % cnt + cnt) % cnt;
  57.                 printf("%d\n", v[idx]), fflush(stdout);
  58.             } else {
  59.                 fprintf(stderr, "Wrong op:%c!\n", op);
  60.             }
  61.         }
  62.     }
  63.     fprintf(stderr, "too many try\n");
  64.  
  65.     return 0;
  66. }
Add Comment
Please, Sign In to add comment