题意
从起点出发,一条路径经过所有点。
分析
因为是有向图,且点是可以重复经过的,所以就会想到强连通分量,分量里面的点是相互可达的,可以看成一个点,这样就可以
缩点了。缩点后的图形成一条简单的链且链头是0号点即可。
int nCase = 0;
int dcmp(double x){
if (fabs(x) < eps) return 0;
return x < 0?-1:1;
}
inline int read(){
char c = getchar();
while (!isdigit(c)) c = getchar();
int x = 0;
while (isdigit(c)) {
x = x * 10 + c - '0';
c = getchar();
}
return x;
}
const int maxn = 1010;
int dfn[maxn], low[maxn], belong[maxn], depth, block;
vector<int> G[maxn];
stack<int> st;
map<int, int> mp;
bool mark[maxn];
int _count;
void dfs(int u) {
dfn[u] = low[u] = ++depth;
st.push(u);
mark[u] = true;
for (int i = 0;i < G[u].size();++i) {
int v = G[u][i];
if (dfn[v] == -1) {
dfs(v);
low[u] = min(low[v], low[u]);
}else if (mark[v]) low[u] = min(low[u], dfn[v]);
}
if (dfn[u] == low[u]) {
block++;
while(true) {
int x = st.top();
st.pop();
mark[x] = false;
belong[x] = block;
if (x == u) break;
}
}
}
void find_scc()
{
block = depth = 0;
memset(dfn ,-1, sizeof dfn);
for (int i = 1;i <= _count;++i)
if (dfn[i] == -1) dfs(i);
}
int in[maxn], out[maxn];
void build() {
memset(in, 0,sizeof in);
memset(out, 0,sizeof out);
for (int i = 1;i <= _count;++i) {
for (int j = 0;j < G[i].size();++j) {
if (belong[i] != belong[G[i][j]]) {
in[belong[G[i][j]]]++;
out[belong[i]]++;
}
}
}
}
int main(int argc, const char * argv[])
{
int t;
cin >> t;
while(t--) {
int n;
scanf("%d", &n);
for (int i = 1;i <= maxn - 1;++i)
G[i].clear();
mp.clear();
_count = 0;
for (int i = 1;i <= n;++i) {
int k, u, v;
cin >> k;
while(k--) {
scanf("%d%d", &u, &v);
if (!mp[u]) mp[u] = ++_count;
if (!mp[v]) mp[v] = ++_count;
G[mp[u]].push_back(mp[v]);
}
}
find_scc();
printf("Case %d: ", ++nCase);
if (block == 1) {
puts("YES");
continue;
}
build();
if (in[belong[mp[0]]] || out[belong[mp[0]]] == 0) {
puts("NO");
continue;
}
int cnt1 = 0, cnt2 = 0, cnt3 = 0;
for (int i = 1;i <= block;++i) {
if (in[i] == 0 && out[i] == 1) cnt1++;
if (in[i] == 1 && out[i] == 0) cnt2++;
if (in[i] == 1 && out[i] == 1) cnt3++;
}
if (cnt1 == 1 && cnt2 == 1 && cnt1 + cnt2 + cnt3 == block) {
puts("YES");
}else puts("NO");
}
return 0;
}