CCF认证 201903-4消息传递接口
题目
代码
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
using namespace std;
char code[669][10002][70] = {0};
void Move_Str(char *Old) // 将字符串向前移动,每次判断的是队列的最前面的那一个
{
{
int i = 0;
char temp[70] = {0};
while((*(Old+i)) != ' ' && (*(Old+i)) != 0)
{
i++;
}
memcpy(temp, Old+i+1, 70);
memcpy(Old, temp, 70);
return;
}
int change_num(char *start) // 将字符串中的那一段变成数字,一开始就是错在这里,没有话考虑到数字很大
{
int num_temp = 0, i = 0;
char str_temp[10] = {0};
while(*(start+i) != ' ' && *(start+i) != 0)
{
str_temp[i] = *(start+i);
i++;
}
str_temp[i] = 0;
num_temp = atoi(str_temp);
return num_temp;
}
int main()
{
int T = 0, n = 0;
cin >> T; cin >> n;
getchar();
int i = 0, j = 0, flag = 0, temp_num = 0, unlock = 0;
int Looked[10002] = {0}, k = 0;
char str_temp[10] = {0};
for(i = 0; i< T; i++)
{
for(j = 0; j< n; j++)
{
gets(code[i][j]);
//cout << code[i][j] << endl;
}
}
for(i = 0; i<T; i++)
{
while(1)
{
flag = 0; unlock = 0;
for(j = 0; j< n; j++)
{
Looked[j] = 0; // 将 Looked数组初始化
if(code[i][j][0] != 0)
flag = 1;
}
if(flag == 0)
{
cout << 0 << endl;
break;
// 表示全部都完成了,也就是不会发生死锁
}
// 判断是否是死锁啊
for(j = 0; j< n; j++)
{
if(Looked[j] == 1)
continue;
if(code[i][j][0] == 'R')
{
temp_num = change_num(code[i][j]+1);
if(code[i][temp_num][0] == 'S' && ((change_num(code[i][temp_num]+1)) == j))
{
Move_Str(code[i][j]);
Move_Str(code[i][temp_num]);
unlock = 1;
Looked[j] = 1;
Looked[temp_num] = 1;
// 这样是不会死锁的
}
}
else
{
temp_num = change_num(code[i][j]+1);
if(code[i][temp_num][0] == 'R' && ((change_num(code[i][temp_num]+1)) == j))
{
Move_Str(code[i][j]);
Move_Str(code[i][temp_num]);
unlock = 1;
Looked[j] = 1;
Looked[temp_num] = 1;
// 这样是不会死锁的
}
}
}
if(unlock == 0)
{
cout << 1 << endl;
break;
// 表示死锁了
}
}
}
return 0;
}