Pagini recente » Cod sursa (job #3309210) | Cod sursa (job #1462553) | Cod sursa (job #2859292) | Cod sursa (job #1794290) | Cod sursa (job #3309217)
#include <fstream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
ifstream cin("obiective.in");
ofstream cout("obiective.out");
int n,m,t,MX;
vector<int> G[32005],curr,cg[32005],dp;
vector<pair<int,int>> A[32005];
vector<vector<int>> ctc;
int idx[32005],low[32005],id,v[32005],inStk[32005],cnt,comp[32005];
stack<int> Stk;
void getCtc(int node)
{
curr.clear();
while(!Stk.empty())
{
auto x=Stk.top();
Stk.pop();
inStk[x]=0;
curr.push_back(x);
if(x==node)
break;
}
ctc.push_back(curr);
}
void Dfs(int x)
{
v[x]=1;
Stk.push(x);
inStk[x]=1;
id++;
idx[x]=id; low[x]=id;
for(auto y:G[x])
{
if(!v[y]) ///fiu
{
Dfs(y);
low[x]=min(low[x],low[y]);
}
else
if(inStk[y]) ///back edge
low[x]=min(low[x],low[y]);
}
if(low[x]==idx[x]) ///last
getCtc(x);
}
void Tarjan()
{
for(int x=1;x<=n;x++)
if(!v[x])
Dfs(x);
/*for(auto x:ctc)
{
for(auto y:x)
cout<<y<<" ";
cout<<"\n";
}*/
}
void unic(vector<int> &v)
{
sort(v.begin(),v.end());
auto last=unique(v.begin(),v.end());
v.erase(last,v.end());
}
void bfs(int x)
{
dp=vector<int>(cnt+5,1e9);
deque<int> dq;
dp[x]=0;
dq.push_front(x);
while(!dq.empty())
{
x=dq.front();
dq.pop_front();
for(auto nou:A[x])
{
int y=nou.first;
int c=nou.second;
if(c==0)
{
if(dp[y]>dp[x])
{
dp[y]=dp[x];
dq.push_front(y);
}
}
else
{
if(dp[y]>dp[x]+1)
{
dp[y]=dp[x]+1;
dq.push_back(y);
}
}
}
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int u,v;
cin>>u>>v;
G[u].push_back(v);
}
Tarjan();
for(auto v:ctc)
{
cnt++;
for(auto x:v)
comp[x]=cnt;
}
for(int x=1;x<=n;x++)
{
for(auto y:G[x])
{
if(comp[x]!=comp[y])
cg[comp[x]].push_back(comp[y]);
}
}
for(int x=1;x<=cnt;x++)
{
unic(cg[x]);
for(auto y:cg[x])
{
A[x].emplace_back(y,0);
A[y].emplace_back(x,1);
}
}
cin>>t;
while(t--)
{
int x,y;
cin>>x>>y;
//bfs(comp[x]);
//cout<<dp[comp[y]]<<"\n";
}
return cnt;
}