1142 Maximal Clique (25 point(s))
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
.
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点集不可以再加入任何一个新的结点构成新的Clique(即是最大的),我们称这样的Clique为Maximal Clique。给定无向图和子集,进行判断。
使用邻接矩阵存储无向图,将给出的子集存储在set<int> s中,按照定义暴力求解。
1. 先判断是不是Clique。遍历s中任意两个元素,如果存在graph[i][j]==false则不是;
2. 再判断是不是Maximal Clique。遍历每一个不在s的元素i,如果存在对于s中所有的j有graph[i][j]==true,则不是;
3. 否则输出“Yes”。
完成本题后的反思:STL中set/vector等查找元素是否存在、个数等库函数
#include<iostream>
#include<cstring>
#include<vector>
#include<set>
using namespace std;
const int N = 207;
int nv,ne;
bool graph[N][N]={false};
set<int> s;
bool isClique(){
set<int>::iterator i;
for(i=s.begin();i!=s.end();i++){
set<int>::iterator j=i;
for( j++;j!=s.end();j++){
if(!graph[(*i)][(*j)]) return false;
}
}
return true;
}
bool isMax(){
for(int i=1;i<=nv;i++){
if(s.find(i)==s.end()){//如果不在这个集合
bool flag = false;
set<int>::iterator it;
for(it=s.begin();it!=s.end();it++){
if(!graph[i][*it]){
flag =true;break;
}
}
if(!flag) return false;
}
}
return true;
}
int main(void){
int a,b,M;cin>>nv>>ne;
while(ne--){
cin>>a>>b;
graph[a][b]=graph[b][a]=true;
}
int K,x;cin>>M;
while(M--){
s.clear();
cin>>K;
while(K--){
cin>>a;
s.insert(a);
}
if(!isClique()) cout<<"Not a Clique"<<endl;
else if(!isMax()) cout<<"Not Maximal"<<endl;
else cout<<"Yes"<<endl;
}
return 0;
}
此题的主要操作是要对特定的边是否存在进行判断,因此使用邻接矩阵更加简单。
大神用向量数组存储的代码: