【递归】POJ-1680 Fork() Makes Trouble

版权声明:Johnson https://blog.csdn.net/m0_38055352/article/details/88824370

这段时间要沉迷刷题一段时间了,就让CSDN陪我一起吧!

1. 题目大意

题目给了一段C程序,其实主要就是Linux下的fork()函数的应用,这个函数的意思就是子程序完全复制父程序的执行以及其执行位置,这里举一个例子帮助大家理解。

#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#define N ???
int main(void){
	int i;
	int ProcessID;
	int A;
	A = 0;
	for(int i=0;i<N;i++){
		printf("Loop %d: Process ID=%d\n", i, getpid());
		A = A + 7;
		while((ProcessID=fork())==-1);
		if(ProcessID==0){
			printf("Process ID=%d, A=%d\n", getpid(), A);
		}
		else {
			wait(NULL);
		}
	}
}

以上是题目代码,fork()到底是什么意思呢?就以第一次父程序进入循环为例,父程序首先进入循环,i=0,打印输出"Loop 0: Process ID=1000",然后A=A+7,然后就到了fork()函数了,这里执行完fork()函数后,系统将再创建一个子进程,而且这个子进程完全复制父进程,就是说这个子进程此时的i=0,A=7,而且也执行到了while((processID=fork())==-1)这条语句,唯一与父进程不同的是ProcessID,子进程的ProcessID为0,父进程为子进程ID。有一点绕,对于没有基础的人可能理解比较困难,但理解之后还是很好做的。

2. 题目思路及AC代码

对于这个问题,可以考虑用递归来进行模拟,但要注意其最终要求输出的结果只有一行,下面给出我的代码(有点丑,请见谅)

#include <iostream>
using namespace std;

int T, N;
int row;
int cnt;
int totalpid;

void init() {
	cnt = 1;
	totalpid = 1000;
}

bool fork(int pid, int A, int idx) {
	if (pid != 1000) {		// 是子进程
		if (cnt == row) {
			printf("Process ID=%d, A=%d\n", pid, A);
			return true;
		}
		else
			cnt++;
	}
	for (int i = idx; i < N; i++) {
		if (cnt == row) {
			printf("Loop %d: Process ID=%d\n", i, pid);
			return true;
		}
		else
			cnt++;
		totalpid++;
		if (fork(totalpid, A += 7, i + 1)) {
			return true;
		}
	}
	return false;
}

int main()
{
	scanf("%d", &T);

	while (T--) {
		init();

		scanf("%d%d", &N, &row);
		fork(1000, 0, 0);
	}

    return 0;
}

欢迎大家指正问题!

猜你喜欢

转载自blog.csdn.net/m0_38055352/article/details/88824370