Description
在操作系统中存在着死锁问题。进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程。
由于资源占用是互斥的,当某个进程提出申请资源后,使得有关进程在无外力协助下,永远分配不到必需的资源而无法继续运行,这就产生了死锁。
例如,如果线程A占用了资源1并等待资源2,而线程B占用了资源2并等待资源1,这样两个线程就发生了死锁现象。
为了描述系统资源分配的问题,我们用一张有向图G来表示资源分配图。V为有向图的顶点集,包括进程结点集合P={p1,p2,…,pn}和资源结点集合R={r1,r2,…,rm}两种;E为有向边的集合,其元素包括二元组(pi,rj)或(rj,pi)。(pi,rj)表示进程pi申请资源rj,(rj,pi)表示资源rj被进程pi占用。
根据操作系统中的知识可以知道,如果在一个资源分配图中,从任意一个结点出发,都不存在一条路径能回到自身,则系统中没有死锁,否则系统中可能存在死锁。
你的任务是对于给你的一张资源分配图,判断是否可能存在死锁。
Input
输入第一行是一个整数T,,表示有T组数据。每组数据的第一行是四个整数P,R,E1,E2,其中P表示进程结点数,R表示资源结点数,E1表示(pi,rj)边数,E2表示(rj,pi)边数,1 <= P,R <= 500。接下来E1行每行两个整数pi,rj,表示从结点pi到rj有一条边。接下来E2行每行两个整数rj,pi,表示从结点rj到pi有一条边。0 <= pi < P, 0 <= rj <R。
Output
对于每组数据输出一行先输出组数(从1开始),接着如果可能存在死锁输出”Possible”;如果不可能存在死锁输出一行“Impossible”。Sample Input
2
2 2 1 1
0 1
0 1
3 3 3 4
0 0
1 1
2 2
0 1
2 0
2 1
1 2
Sample Output
Case 1: Impossible
Case 2: Possible
分析:简单的判环问题,进行深度优先搜索,在一次搜索中将一个点的颜色设为1,退出是设为2,如果搜索到了颜色为1的点,则说明有环。
#include<stdio.h>
struct edge{
int to;
edge *next;
};
struct node{
int color;
edge *next;
};
node source[505],process[505];
int flag,na,nb;
void processDfsVis(int);
void sourceDfsVis(int);
void dfs();
void processAdd(int a,int b)
{
edge *l=new(edge);
l->to=b;
l->next=process[a].next;
process[a].next=l;
}
void sourceAdd(int a,int b)
{
edge *l=new(edge);
l->to=b;
l->next=source[a].next;
source[a].next=l;
}
int main()
{
int ncas=1,T,ma,mb,i,a,b;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d%d",&na,&nb,&ma,&mb);
for(i=0;i<na;i++)
process[i].next=NULL;
for(i=0;i<nb;i++)
source[i].next=NULL;
while(ma--)
{
scanf("%d%d",&a,&b);
processAdd(a,b);
}
while(mb--)
{
scanf("%d%d",&a,&b);
sourceAdd(a,b);
}
flag=1;
dfs();
printf("Case %d:",ncas++);
if(flag)puts(" Impossible");
else puts(" Possible");
}
return 0;
}
void sourceDfsVis(int i)
{
int x;
source[i].color=1;
edge *l=source[i].next;
while(l)
{
x=l->to;
if(process[x].color==0)processDfsVis[x];
else if(process[x].color==1)flag=0;
l=l->next;
}
source[i].color=2;
}
void processDfsVis(int i)
{
int x;
process[i].color=1;
edge *l=process[i].next;
while(l)
{
x=l->to;
if(source[x].color==0)sourceDfsVis(x);
else if(source[x].color==1)flag=0;
l=l->next;
}
process[i].color=2;
}
void dfs()
{
int i;
for(i=0;i<nb;i++)
source[i].color=0;
for(i=0;i<na;i++)
process[i].color=0;
for(i=0;i<nb;i++)
if(source[i].color==0)
sourceDfsVis(i);
for(i=0;i<na;i++)
if(process[i].color==0)
processDfsVis(i);
}