PAT Advanced 1142 Maximal Clique (25) [图论,⽆向完全图,团,极大团]
题目
A clique is a subset of vertices of an undirected graph such that every two distinct vertices in the clique are adjacent. A maximal clique is a clique that cannot be extended by including one more adjacent vertex. (Quoted from https://en.wikipedia.org/wiki/Clique_ (graph_theory)) Now it is your job to judge if a given subset of vertices can form a maximal clique.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers Nv (<= 200), the number of vertices in the graph, and Ne, the number of undirected edges. Then Ne lines follow, each gives a pair of vertices of an edge. The vertices are numbered from 1 to Nv. Afer the graph, there is another positive integer M (<= 100). Then M lines of query follow, each first gives a positive number K (<= Nv), then followed by a sequence of K distinct vertices. All the numbers in a line are separated by a space.
Output Specification:
For each of the M queries, print in a line “Yes” if the given subset of vertices can form a maximal clique; or if it is a clique but not a maximal clique, print “Not Maximal”; or if it is not a clique at all, print “Not a Clique”.
Sample Input:
8 10
5 6
7 8
6 4
3 6
4 5
2 3
8 2
2 7
5 3
3 4
6
4 5 4 3 6
3 2 8 7
2 2 3
1 1
3 4 3 6
3 3 2 1
Sample Output:
Yes
Yes
Yes
Yes
Not Maximal
Not a Clique
题目分析
团clique(clique)是一个无向图(undirected graph )的子图,该子图中任意两个顶点之间均存在一条边。
极大团maximal clique是一个团,该团不能被更大的团所包含,换句话说,图中再也不存在一个点与该团中的任意顶点之间存在一条边。
已知一系列测试样例,判断每个测试样例中的顶点是否为可组成团,若是团,判断是否为极大团
极大图条件:
- 极大团中所有顶点在图中两两间有边
- 图中再没有一个顶点与极大团顶点间存在边
解题思路
- 存储图(邻接矩阵)
- 判断每个顶点集是否为极大团,若是团,判断是否为极大团
Code
#include <iostream>
using namespace std;
const int maxn=210;
int nv,ne,e[maxn][maxn];
int main(int argc,char * argv[]) {
scanf("%d %d",&nv,&ne);
int a,b,m,k;
for(int i=1; i<=ne; i++) {
scanf("%d %d",&a,&b);
e[a][b]=e[b][a]=1;
}
scanf("%d",&m);
for(int i=0; i<m; i++) {
scanf("%d", &k);
int cv[maxn]= {0},incv[maxn]= {0};
for(int j=0; j<k; j++) {
scanf("%d", &cv[j]);
incv[cv[j]]=1;
}
// 判断是否为clique
bool isClique=true,isMaximal=true;
for(int j=0; j<k; j++) {
if(isClique==false)break;
for(int r=j+1;r<k;r++){ //0~j已经跟子顶点集合中任意顶点匹配过,无需再匹配
if(e[cv[j]][cv[r]]==0){
isClique=false;
printf("Not a Clique\n");
break;
}
}
}
if(isClique==false)continue;
// 判断是否为 maximal clique
for(int j=1;j<=nv;j++){
if(incv[j]==1)continue; //在子顶点集合中的点跳过
for(int r=0;r<k;r++){
if(e[j][cv[r]]==0)break; //如果边不存在,退出循环,继续下个剩余顶点校验
if(r==k-1)isMaximal=false; //如果存在顶点与Clique中所有顶点有相邻有边,则可将该节点加入Clique中,所以原Clique不是最大Clique
}
if(isMaximal==false){
printf("Not Maximal\n");
break;
}
}
if(isMaximal&&isClique){
printf("Yes\n");
}
}
return 0;
}