Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <cstdio>
- using namespace std;
- class node;
- class node{
- public:
- int el;
- int d;
- node* next;
- node* prev;
- node(int a, node* p)
- {
- el=a;
- next=NULL;
- prev=p;
- }
- node(int a, int dt, node* p)
- {
- el=a;
- d=dt;
- next=NULL;
- prev=p;
- }
- };
- class node_G{
- public:
- node* first;
- node* last;
- node_G()
- {
- first=NULL;
- last=NULL;
- }
- };
- int jfind(int* j, int a)
- {
- if(j[a]!=a)
- {
- return jfind(j, j[a]);
- }
- else
- {
- return a;
- }
- }
- node_G** push(node_G** g, int A, int B)
- {
- if(g[A]->last==NULL)
- {
- g[A]->first=new node(B,NULL);
- g[A]->last=g[A]->first;
- }
- else
- {
- g[A]->last->next=new node(B,g[A]->last);
- g[A]->last=g[A]->last->next;
- }
- if(g[B]->last==NULL)
- {
- g[B]->first=new node(A,NULL);
- g[B]->last=g[B]->first;
- }
- else if(A!=B)
- {
- g[B]->last->next=new node(A,g[B]->last);
- g[B]->last=g[B]->last->next;
- }
- return g;
- }
- node_G** cont(node_G** g, int* j, int* Nv, int A, int B)
- {
- int Aj=jfind(j, A);
- int Bj=jfind(j, B);
- if(Aj != Bj && g[Bj]->first!=NULL)
- {
- g[Aj]->last->next=g[Bj]->first;
- g[Aj]->last=g[Bj]->last;
- g[Bj]->first=g[Aj]->first;
- j[Bj]=Aj;
- (*Nv)--;
- return g;
- }
- return g;
- }
- int dist(node_G** g, int Nv, int* j, int A, int B)
- {
- int ct=0;
- int s=jfind(j, A);
- int r=jfind(j, B);
- int v[Nv];
- for(int i=0; i<Nv; i++)
- {
- v[i]=-1;
- }
- node_G q;
- q.first = new node(s, 0, NULL);
- q.last=q.first;
- v[s]=ct++;
- while(q.first!=NULL)
- {
- node* a;
- node* vert = (node*)malloc(sizeof(node));
- vert->el = q.first->el;
- vert->next = q.first->next;
- vert->d = q.first->d;
- node* fwd=q.first->next;
- free(q.first);
- q.first=fwd;
- if(fwd==NULL)
- {
- q.last = NULL;
- }
- for (a = g[vert->el]->first; a != NULL; a = a->next)
- {
- int tp=jfind(j, a->el);
- if(r==tp)
- {
- return vert->d+1;
- }
- if (v[tp] == -1)
- {
- v[tp] = ct++;
- if(q.last!=NULL)
- {
- q.last->next= new node(tp, vert->d+1, NULL);
- q.last=q.last->next;
- }
- else
- {
- q.first = new node(tp, vert->d+1, NULL);
- q.last=q.first;
- }
- }
- }
- }
- return -1;
- }
- int main()
- {
- ios::sync_with_stdio(false);
- cin.tie(NULL);
- int N, M, A, B, O, Nv;
- char op;
- cin >> N >> M;
- Nv=N;
- int* join = (int*)malloc(sizeof(int)*N);
- node_G** adj = (node_G**)malloc(sizeof(node_G*)*N);
- for(int i=0; i<N; i++)
- {
- join[i]=i;
- adj[i] = new node_G();
- }
- for(int i=0; i<M; i++)
- {
- cin >> A >> B;
- adj=push(adj, A, B);
- }
- cin >> O;
- for(int i=0; i<O; i++)
- {
- cin >> op >> A >> B;
- if(op=='c')
- {
- adj=cont(adj, join, &Nv, A, B);
- cout << Nv << "\n";
- }
- else
- {
- int wtf=dist(adj, Nv, join, A, B);
- cout << wtf << "\n";
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement