#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> pi;
typedef vector<pi> vpi;
#define all(x) x.begin(),x.end()
#define out(x) {cout << x << "\n"; return;}
#define GLHF ios_base::sync_with_stdio(0); cin.tie(0)
#define pb push_back
void solve();
int main(){
GLHF;
solve();
}
vi up;
vi par,rnk,dep;
int get(int x) { return par[x] = (x == par[x] ? x : get(par[x])); }
void unite(int u, int v) {//u in new leader
u = get(u), v = get(v);
if (u == v)return;
if (rnk[u] > rnk[v])
swap(u, v);
par[u] = v;
rnk[v] += rnk[u];
}
vector<set<int>> inv;//inv[i]= {j s.t par[j]=i} = {kids of i}
set<pi>ans;
void dfs(int src,int p=0){
//dep is maintain-able
if(src==-1 )
return;
dfs(up[src],src);
up[src]=p;
if(p!=-1)
dep[src]=dep[p]+1;
inv[src].erase(p);
inv[p].insert(src);
}
void add_edge(int u,int v){
ans.insert({min(u,v),max(u,v)});
if(rnk[get(u)]<rnk[get(v)])
swap(u,v);
//deg[u]>deg[v], re-root at v
dep[v]=dep[u]+1;
dfs(v);
up[v]=u;
inv[u].insert(v);
}
void solve(){
int n,m;
cin >> n >> m;
up.resize(n+1,-1);
dep.resize(n+1);
par.resize(n+1);
rnk.resize(n+1,1);
for(int i=0; i<=n; i++)
par[i]=i;
inv.resize(n+1);
for(int i=0; i<m; i++){
int u,v;
cin >> u >> v;
if(u==v)
continue;
if(get(u)!=get(v)){
add_edge(u,v);
unite(u,v);
continue;
}
vector<bool>vis(n+1);
int x=u;
while(x!=-1){
vis[x]=1;
x=up[x];
}
int l=v;
while(!vis[l])
l=up[l];
while(v!=l){
ans.erase({min(v,up[v]),max(v,up[v])});
v=up[v];
}
while(u!=l){
ans.erase({min(u,up[u]),max(u,up[u])});
u=up[u];
}
}
for(pi p:ans)
cout << p.first << " " << p.second << "\n";
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
384 KB |
Output is correct |
2 |
Correct |
1 ms |
204 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
36 ms |
1012 KB |
Output is correct |
2 |
Correct |
20 ms |
972 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
747 ms |
6108 KB |
Output is correct |
2 |
Correct |
402 ms |
6068 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1983 ms |
11124 KB |
Output is correct |
2 |
Correct |
1230 ms |
12984 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Runtime error |
3994 ms |
19652 KB |
Memory limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
5060 ms |
15320 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
5096 ms |
15512 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
5098 ms |
17804 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
5088 ms |
17940 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
5057 ms |
17636 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |