QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#414766#6559. A Tree and Two Edgeskaruna#RE 0ms0kbC++202.1kb2024-05-19 17:03:172024-05-19 17:03:17

Judging History

你现在查看的是最新测评结果

  • [2024-05-19 17:03:17]
  • 评测
  • 测评结果:RE
  • 用时:0ms
  • 内存:0kb
  • [2024-05-19 17:03:17]
  • 提交

answer

#include <bits/stdc++.h>
#define ff first
#define ss second
using namespace std;

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const int MAXN = 5e4;


int N, Q;
vector<int> adj[MAXN+10];
vector<vector<int>> V;
vector<pii> E;

int vis[MAXN+10], par[MAXN+10];
void dfs(int now, int bef)
{
	vis[now]=1;
	par[now]=bef;
	for(int nxt : adj[now])
	{
		if(nxt==bef) continue;
		if(vis[nxt]==0) dfs(nxt, now);
		if(vis[nxt]==1)
		{
			vector<int> VV;
			for(int i=now; i!=nxt; i=par[i]) VV.push_back(i);
			VV.push_back(nxt);
			V.push_back(VV);
		}
	}
	vis[now]=2;
}

bool P[MAXN+10];
int P2[MAXN+10];
bool chk(int u, int v)
{
	if(u>v) swap(u, v);
	P[lower_bound(E.begin(), E.end(), pii(u, v))-E.begin()]=1;
}

struct UF
{
	int par[MAXN+10];
	void init()
	{
		for(int i=1; i<=N; i++) par[i]=i;
	}
	int Find(int x)
	{
		if(x==par[x]) return x;
		return par[x]=Find(par[x]);
	}
	void Union(int x, int y)
	{
		x=Find(x);
		y=Find(y);
		par[x]=y;
	}
}uf;

int main() {
	cin.tie(0); ios_base::sync_with_stdio(0);

	scanf("%d%d", &N, &Q);
	for(int i=1; i<=N+1; i++)
	{
		int u, v;
		scanf("%d%d", &u, &v);
		if(u>v) swap(u, v);
		E.push_back({u, v});
		adj[u].push_back(v);
		adj[v].push_back(u);
	}

	uf.init();
	sort(E.begin(), E.end());

	dfs(1, 1);
	assert(V.size()==2);

	for(int i=0; i+1<V[0].size(); i++) chk(V[0][i], V[0][i+1]);
	chk(V[0][V[0].size()-1], V[0][0]);
	
	for(int i=0; i+1<V[1].size(); i++) chk(V[1][i], V[1][i+1]);
	chk(V[1][V[1].size()-1], V[1][0]);

	for(int i=0; i<E.size(); i++)
	{
		if(P[i]) continue;
		uf.Union(E[i].first, E[i].second);
	}

    for(auto jt : V[0]) P2[uf.Find(jt)]|=1;
	for(auto jt : V[1]) P2[uf.Find(jt)]|=2;

	int cnt=0;
	for(int i=1; i<=N; i++) if(P2[i]==3) cnt++;

	while(Q--)
	{
		int u, v;
		scanf("%d%d", &u, &v);
		if(uf.Find(u)==uf.Find(v)) printf("1\n");
		else if(P2[uf.Find(u)]==3 || P2[uf.Find(v)]==3)
		{
			if(cnt==1) printf("2\n");
			else printf("3\n");
		}
		else if(P2[uf.Find(u)]==P2[uf.Find(v)])
		{
			if(cnt==1) printf("2\n");
			else printf("3\n");
		}
		else printf("4\n");
	}
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 0
Runtime Error

input:

4 6
1 2
1 3
1 4
2 3
2 4
1 2
1 3
1 4
2 3
2 4
3 4

output:


result: