105322024-04-04 17:40:28111Kutyavetélkedő 2cpp17Wrong answer 0/100435ms124044 KiB
#include<bits/stdc++.h>
using namespace std;

#define int long long

void scc_dfs(const auto&g,auto&v,auto&s,int i){
	if(v[i]){
		return;
	}
	v[i]=1;
	for(int j:g[i]){
		scc_dfs(g,v,s,j);
	}
	s.push_back(i);
}

int scc(const auto&g,const auto&gg,auto&c){
	int n=g.size();
	vector<int>v,s;
	v.assign(n,0);
	for(int i=0;i<n;i++){
		scc_dfs(g,v,s,i);
	}
	v.assign(n,0);
	for(int i=n-1;i>=0;i--){
		if(v[s[i]]){
			continue;
		}
		c.emplace_back();
		scc_dfs(gg,v,c.back(),s[i]);
	}
	return c.size();
}

signed main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int N,K;
	cin>>N>>K;
	vector<int>v(N);
	for(int i=0;i<N;i++){
		cin>>v[i];
	}
	int M;
	cin>>M;
	vector<vector<int>>g(K+1),gg(K+1);
	for(int i=0;i<M;i++){
		int a,b;
		cin>>a>>b;
		g[a].push_back(b);
		gg[b].push_back(a);
	}
	vector<vector<int>>c;
	int O=scc(g,gg,c);
	vector<int>cc(K+1);
	for(int i=0;i<O;i++){
		for(int j:c[i]){
			cc[j]=i;
		}
	}
	vector<vector<int>>h(O);
	for(int i=0;i<O;i++){
		for(int j:c[i]){
			for(int k:g[j]){
				int l=cc[k];
				if(l!=i){
					h[i].push_back(l);
				}
			}
		}
	}
	for(int i=0;i<O;i++){
		sort(h[i].begin(),h[i].end());
		h[i].erase(unique(h[i].begin(),h[i].end()),h[i].end());
	}
	for(int i=1;i<=K;i++){
		sort(g[i].begin(),g[i].end());
	}
	int ans=2;
	int last=cc[v[0]];
	vector<int>w(O);
	deque<int>q;
	for(int i=0;i+1<N;i++){
		if(binary_search(g[v[i]].begin(),g[v[i]].end(),v[i+1])){
			ans+=2;
			continue;
		}
		int next=cc[v[i+1]];
		w[last]=1;
		q.push_back(last);
		while(!q.empty()&&last!=next){
			int i=q.front();
			q.pop_front();
			for(int j:h[i]){
				if(w[j]){
					continue;
				}
				w[j]=1;
				q.push_back(j);
				if(j==next){
					last=j;
					q.clear();
					break;
				}
			}
		}
		if(last!=next){
			break;
		}
		ans+=1;
	}
	cout<<ans<<'\n';
	return 0;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms1824 KiB
2Accepted3ms2060 KiB
subtask20/21
3Accepted3ms2404 KiB
4Accepted3ms2620 KiB
5Accepted3ms2828 KiB
6Accepted3ms3168 KiB
7Accepted3ms3360 KiB
8Wrong answer3ms3204 KiB
9Accepted3ms3456 KiB
subtask30/45
10Wrong answer71ms16720 KiB
11Wrong answer71ms16816 KiB
12Wrong answer100ms30324 KiB
13Wrong answer104ms30560 KiB
14Wrong answer101ms30568 KiB
15Wrong answer100ms30808 KiB
16Wrong answer105ms34592 KiB
17Wrong answer125ms38356 KiB
18Wrong answer118ms40416 KiB
19Wrong answer118ms40720 KiB
20Wrong answer116ms40852 KiB
subtask40/34
21Wrong answer232ms56700 KiB
22Wrong answer287ms75092 KiB
23Wrong answer337ms94412 KiB
24Accepted435ms124044 KiB
25Wrong answer345ms94392 KiB
26Wrong answer293ms75132 KiB