思路
1)T是测试几次。n是每次有几个程序。
2)命令后面的数字可能是多位数,例如”S123“
3)判断死锁没有,就是看当前所有程序的当前命令是否是:
<1>全是S命令 或者 全是R命令
<2>S命令 或者 R命令后面指定的程序是不存在的,例如n=10,存在S11命令,11不存在。
<3>S命令指定的程序,当前命令不是R
代码
#include <stdio.h>
#include <string.h>
typedef struct{
char cmd[10][100];
int cmdCount;
int deal;
} Program;
int getIndex(char *s);
Program cx[10000];
char sdf[1000];
int main(){
int T,n,i,j,k,h,len,sIndex,rIndex;
scanf("%d %d",&T,&n);
getchar();
char ch;
for(i=0; i<T; i++){
for(j=0; j<n; j++){
k=0;
cx[j].deal = cx[j].cmdCount = 0;
gets(sdf);
len = strlen(sdf);
h = 0;
while(h<len){
ch = sdf[h++];
if(ch==' '){
cx[j].cmd[cx[j].cmdCount][k]='\0';
cx[j].cmdCount++;
k=0;
}else{
cx[j].cmd[cx[j].cmdCount][k]=ch;
k++;
}
}
cx[j].cmd[cx[j].cmdCount][k]='\0';
cx[j].cmdCount++;
}
int cnt=0,flag=0;
for(j=0; ; j++){
if(cnt == n){
printf("0\n");
break;
}
if(j==n){
if(flag == 0){
printf("1\n");
break;
}
flag = 0;
j = 0;
}
len = strlen(cx[j].cmd[cx[j].deal]);
if(cx[j].deal < cx[j].cmdCount && cx[j].cmd[cx[j].deal][0]=='S'){
sIndex = getIndex(cx[j].cmd[cx[j].deal]);
if(sIndex >= n){
printf("1\n");
break;
}
if(cx[sIndex].deal < cx[sIndex].cmdCount
&& cx[sIndex].cmd[cx[sIndex].deal][0]=='R'){
rIndex = getIndex(cx[sIndex].cmd[cx[sIndex].deal]);
if(rIndex >= n){
printf("1\n");
break;
}
if(rIndex == j){
cx[j].deal++;
cx[sIndex].deal++;
if(cx[j].deal==cx[j].cmdCount) cnt++;
if(cx[sIndex].deal==cx[sIndex].cmdCount) cnt++;
flag = 1;
}
}
}
}
}
return 0;
}
int getIndex(char *s){
s++;
int len = strlen(s);
int times=1,i;
for(i=1; i<len; i++){
times*=10;
}
int index=0;
for(i=0; i<len; i++){
index+=(s[i]-'0')*times;
times/=10;
}
return index;
}
注意点
gets(sdf);
len = strlen(sdf);
h = 0;
while(h<len){
ch = sdf[h++];
这部分代码写成
while(1>0){
ch = getchar()
if(ch=='\n) break;
会报“运行错误”具体原因我现在也没搞懂为啥。没看出啥不对劲的地方。我自己测试是没毛病的。