F. Upgrading Cities
time limit per test 2 seconds
memory limit per test 256 megabytes
inputstandard input
outputstandard output
There are n cities in the kingdom X, numbered from 1 through n. People travel between cities by some one-way roads. As a passenger, JATC finds it weird that from any city u, he can’t start a trip in it and then return back to it using the roads of the kingdom. That is, the kingdom can be viewed as an acyclic graph.
Being annoyed by the traveling system, JATC decides to meet the king and ask him to do something. In response, the king says that he will upgrade some cities to make it easier to travel. Because of the budget, the king will only upgrade those cities that are important or semi-important. A city u is called important if for every city v≠uv≠uv̸=u, there is either a path from u to v or a path from v to u. A city u is called semi-important if it is not important and we can destroy exactly one city v≠uv≠uv̸=u so that u becomes important.
The king will start to act as soon as he finds out all those cities. Please help him to speed up the process.
Input
The first line of the input contains two integers n and m (2≤n≤300000,1≤m≤300000)(2≤n≤300000, 1≤m≤300000)(2≤n≤300000,1≤m≤300000) — the number of cities and the number of one-way roads.
Next m lines describe the road system of the kingdom. Each of them contains two integers uiu_iui and viv_ivi (1≤ui,vi≤n,ui≠vi)(1≤u_i,v_i≤n, u_i≠v_i)(1≤ui,vi≤n,ui̸=vi), denoting one-way road from uiu_iui to viv_ivi.
It is guaranteed, that the kingdoms’ roads make an acyclic graph, which doesn’t contain multiple edges and self-loops.
Output
Print a single integer — the number of cities that the king has to upgrade.
Examples
input
7 7
1 2
2 3
3 4
4 7
2 5
5 4
6 4
output
4
input
6 7
1 2
2 3
3 4
1 5
5 3
2 6
6 4
output
4
思路:题意很清楚,只要对于每个点,求出能到达它的点数和它能到达的点数之和。
考虑拓扑排序的过程。
用一个变量tot记录当前还未访问的点的数量,当队列中只有一个点时,那么这个点肯定能到达剩下的tot个点,将tot记录下来;若队列中有2个点,那么判断当前出队列的这个点的儿子是否包含另一个点的所有儿子,如果是,那么这个点能到达剩下的tot个点,否则到达不了,那对答案就没有贡献,所以直接舍弃即可;若队列中的点不止2个,那么这些点肯定也都对答案没有贡献,直接舍弃即可。
因为要求出能到达它的点数和它能到达的点数,所以还需将所有的边反向再来一次。
最后判断对于每个点记录下来的点数是否大于等n-2。
#include<bits/stdc++.h>
using namespace std;
const int MAX=3e5+10;
vector<int>e[MAX];
int in[MAX];
int d[MAX];
int n,m;
void cal(int *u,int *v)
{
memset(in,0,sizeof in);
for(int i=1;i<=n;i++)e[i].clear();
for(int i=1;i<=m;i++)
{
e[u[i]].push_back(v[i]);
in[v[i]]++;
}
int tot=n;
queue<int>p;
for(int i=1;i<=n;i++)if(in[i]==0)p.push(i),tot--;
while(!p.empty())
{
int x=p.front();p.pop();
if(p.empty())d[x]+=tot;
if(p.size()==1)
{
int c=1;
for(int i=0,y=p.front();i<e[y].size();i++)c&=(in[e[y][i]]>1);
d[x]+=c*tot;
}
for(int i=0;i<e[x].size();i++)if(!--in[e[x][i]]){p.push(e[x][i]),tot--;}
}
}
int u[MAX],v[MAX];
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)scanf("%d%d",&u[i],&v[i]);
cal(u,v);
cal(v,u);
int ans=0;
for(int i=1;i<=n;i++)ans+=(d[i]>=n-2);
cout<<ans<<endl;
return 0;
}