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.
After 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.
题解:
这道题本来想用邻接表来实现,但后来发现邻接矩阵对于我来说更好理解和使用,我就选取了邻接矩阵来存储邻接信息,用一个动态数组和bool数组存储了测试序列信息,首先判断这些序列里两两结点是否邻接,若出现一个不邻接,则直接输出no并返回,若是;
(到这里其实我的思路有些混乱了,所以去参考了一下其他优秀的代码,发现前面思路是一样的,而它的思路是选择用剩下的点来遍历,只要发现一个点能和序列里所有点邻接,就不是maximal,遍历完如果没有这样的点,则是maximal)
代码:
#include<iostream>
#include<vector>
using namespace std;
const int maxv=209;
int nv;
int Adj[maxv][maxv]={0};
void check(int index){
int k;
cin>>k;
bool vis[nv+1]={false};
vector<int> order(k);
for(int i=0;i<k;i++){
cin>>order[i];
vis[order[i]]=true;
}
int isMax=1;
for(int i=0;i<k;i++){
for(int j=i+1;j<k;j++){
if(Adj[order[i]][order[j]]==0){
printf("Not a Clique\n");
return;
}
}
}
for(int i=1;i<=nv;i++){
if(vis[i]==false){
int flag=1;
for(int j=0;j<order.size();j++){
if(Adj[i][order[j]]==0){ //该节点不是和所有的点都邻接
flag=0;
}
}
if(flag==1){
printf("Not Maximal\n");
return;
}
}
}
printf("Yes\n");
return;
}
int main(){
int ne,e1,e2,m,k;
cin>>nv>>ne;
while(ne--){
cin>>e1>>e2;
Adj[e1][e2]=Adj[e2][e1]=1; //在邻接矩阵e1和e2上互相标记
}
cin>>m;
for(int index=0;index<m;index++) check(index);
}
其实这两天做题总有种体会,就是自己的思路还需再多锻炼多锻炼,因为总感觉自己想得太绕太复杂,导致思路混乱。