题目:
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3811
题意:
给定一个无向图,及一个结点序列,不一定包括图上所有结点,可以从任一点开始遍历,允许走重复路径,问能否按照结点顺序遍历全图
思路:
搜索染色。
对序列中的每个点做搜索,BFS、DFS均可,对序列第i个点遍历图上所有可由i点到达且不经过任一序列中的点,若搜索到序列中的点则标记但不继续搜索,遍历一条边就删掉它,对序列扫一遍的过程中,发现某个点未被标记则说明它无法由序列中在它前面的点不经过在它之后的点到达,输出“NO”,扫完检查一遍是否每个点都搜索过了防不连通图的数据。
代码:
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string.h>
using namespace std;
const int MAXSIZE = 1e5 + 10;
bool vis[MAXSIZE];
bool isreco[MAXSIZE];
int arr[MAXSIZE];
struct Edge{
int from,to;
bool vis;
};
Edge edges[4 * MAXSIZE];
int first[MAXSIZE],gnext[4 * MAXSIZE],esum;
int n,m,k,l;
void init(){
esum = -1;
memset(first,-1,sizeof(int)*(n+5));
memset(vis,0,sizeof(bool)*(n+5));
memset(isreco,0,sizeof(bool)*(n+5));
}
void addEdge(int from, int to){
gnext[++esum] = first[from];
first[from] = esum;
Edge e = {from, to, false};
edges[esum] = e;
}
void dfs(int x){
//cout<<x<<endl;
vis[x] = true;
//cout<<"vis"<<x<<endl;
int i = first[x];
while (i!=-1){
//cout<<x<<" "<<i<<endl;
Edge& e = edges[i];
//cout<<"edge: "<<x<<" "<<e.from<<" "<<e.to<<endl;
if (e.vis) {i = gnext[i];continue;}
e.vis = true;
edges[i^1].vis = true;
if (vis[e.to]){
i = gnext[i];
continue;
}
if (isreco[e.to]){
vis[e.to] = true;
//cout<<"vis"<<e.from<<" "<<e.to<<endl;
i = gnext[i];
continue;
}
dfs(e.to);
i = gnext[i];
}
}
int main(){
int total;
cin>>total;
while (total--){
scanf("%d %d %d",&n,&m,&k);
init();
int a,b,c;
for (int i=0;i<k;++i){
scanf("%d",&a);
isreco[a] = true;
}
for (int i=0;i<m;++i){
scanf("%d %d",&a,&b);
addEdge(a,b);
addEdge(b,a);
}
scanf("%d",&l);
for (int i=0;i<l;++i){
scanf("%d",arr+i);
}
//cout<<"done"<<endl;
bool flag = true;
if (l<k) flag = false;
else{
vis[arr[0]] = true;
for (int i=0;i<l;++i){
if (vis[arr[i]]) dfs(arr[i]);
else {flag = false;break;}
}
if (flag){
for (int i=1;i<=n;++i){
if (!vis[i]) {flag = false;break;}
}
}
}
if (flag) printf("Yes\n");
else printf("No\n");
}
return 0;
}