題目鏈接:點擊查看
題目大意:給出一張 n 個點和 m 條邊組成的有向無環圖,規定:每個點的出度一定小於等於 2 ,現在要求刪除掉至多 個點,使得任意一條路徑的長度都不大於 1
題目分析:主要是這個出度小於等於 2 和 4/7 有點難搞,在看過題解後,可以這樣考慮,因爲每個點的出度都小於等於 2 ,那麼我們不妨令其出度都爲 2 ,可以得到一顆完全二叉樹:
這樣的話,一個高度爲三的完全二叉樹,恰好有 7 個結點,如果我們將第三層的 4 , 5 , 6 , 7 這四個結點都刪除掉的話,剩下的結點顯然是滿足題意的,這樣我們也就很巧妙的用到了題目給出的兩個條件
換句話說,可以枚舉每個頂點,將與該頂點可能構成長度爲 2 路徑的頂點都刪掉即可,但是這樣處理的話會有後效性,例如:
這樣的一種圖,我們會發現,在枚舉頂點 1 的時候,就已經將點 3 , 4 , 5 都刪掉了,但是這個例子我們只需要刪掉 3 和 4 即可
注意一下題意給的提示,因爲題意給的每條邊 x -> y 都滿足了 x < y ,所以 1 ~ n 的序列就已經滿足拓撲排序了,對於任意一個節點 i 來說,前面的 i - 1 個結點肯定是不會再有影響了,所以我們可以倒着向前找,這個倒着的意思是將整個圖置反,以節點 i 爲起點向前去找,如果找到長度爲 2 的路徑的頂點時,將頂點 i 刪掉即可,這樣的查找就不具有後效性了
代碼:
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=2e5+100;
vector<int>node[N];
bool vis[N];
int main()
{
#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);
int w;
cin>>w;
while(w--)
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
node[i].clear();
vis[i]=false;
}
for(int i=1;i<=m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
node[v].push_back(u);
}
vector<int>ans;
for(int i=1;i<=n;i++)
{
for(auto u:node[i])
if(!vis[u])
for(auto v:node[u])
if(!vis[v])
{
vis[i]=true;
ans.push_back(i);
goto end;
}
end:;
}
printf("%d\n",ans.size());
for(auto it:ans)
printf("%d ",it);
puts("");
}
return 0;
}