The main topic: There are n lights, need to light them all, then there is M-line U,v said U Lit, V is also lit, asked at least a few lights to light;
Problem Analysis: Tarjan first to find all the strong connectivity components, Map[i] that the first point in the first few strong connected components, and then we need DFS each strong connected component, if found Map[u]!=map[v], that is, two strong connected components have an edge between, So that one side can be shed, because we can always in the map[u] in the component of the other component to reach any edge;
AC Code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<stack>
using namespace std;
const int MAX=10010;
vector<int>vec[MAX];
int map[MAX],dfn[MAX],low[MAX],tot[MAX],depth,scc,ans,n,m;
stack<int>s;
void init()
{
int i;
depth=scc=ans=0;
for(i=0;i<MAX;i++)
vec[i].clear();
memset(map,-1,sizeof(map));
memset(tot,0,sizeof(tot));
memset(low,0,sizeof(low));
memset(dfn,-1,sizeof(dfn));
}
void tarjan(int u)
{
int i;
dfn[u]=low[u]=depth++;
s.push(u);
for(i=0;i<vec[u].size();i++)
{
int v=vec[u][i];
if(dfn[v]==-1)
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(map[v]==-1)
low[u]=min(low[u],dfn[v]);
}
if(low[u]==dfn[u])
{
int v;
do{
v = s.top();
map[v] = scc;
s.pop();
}while(v!=u);
scc++;
}
}
void dfs(int u)
{
int i,v;
dfn[u]=1;
for(i=0;i<vec[u].size();i++)
{
v=vec[u][i];
if(map[u]!=map[v]) tot[map[v]]++;
if(!dfn[v]) dfs(v);
}
}
int main()
{
int cas,c,i,u,v;
scanf("%d",&cas);
for(c=1;c<=cas;c++)
{
init();
scanf("%d%d",&n,&m);
for(i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
u--;
v--;
vec[u].push_back(v);
}
for(i=0;i<n;i++)
if(dfn[i]==-1)
tarjan(i);
memset(dfn,0,sizeof(dfn));
for(i=0;i<n;i++)
if(!dfn[i])
dfs(i);
for(i=0;i<scc;i++)
{
if(!tot[i])
ans++;
}
printf("Case %d: %d\n",c,ans);
}
return 0;
}