思路
邻接矩阵的话,直接按主对角线交换就行。 邻接表也比较简单,遍历所有链表,然后将反向的边插入新图。
代码
import java. util. *;
public class Main {
static final int NN= 100100 ;
static private class Graph {
private
Vector< Vector< Integer> > con;
int n;
public
void init ( int xx) {
n= xx;
con= new Vector < Vector< Integer> > ( NN) ;
con. clear ( ) ;
for ( int i= 1 ; i<= n+ 10 ; i++ ) {
Vector< Integer> temp= new Vector < Integer> ( ) ;
temp. clear ( ) ;
con. addElement ( temp) ;
}
}
Graph ( int xx) {
init ( xx) ;
}
void addEdge ( int x, int y) {
Vector < Integer> temp= new Vector < Integer> ( ) ;
temp= con. get ( x) ;
temp. addElement ( ( Integer) y) ;
con. set ( x, temp) ;
}
void printGraph ( ) {
for ( int i= 1 ; i<= n; i++ ) {
for ( int j= 0 ; j< con. get ( i) . size ( ) ; j++ ) {
System. out. printf ( "%d " , con. get ( i) . get ( j) ) ;
}
System. out. printf ( "\n" ) ;
}
}
Graph opst ( ) {
Graph ans= new Graph ( n) ;
for ( int i= 1 ; i<= n; i++ ) {
int sz= con. get ( i) . size ( ) ;
for ( int j= 0 ; j< sz; j++ ) {
ans. addEdge ( con. get ( i) . get ( j) , i) ;
}
}
return ans;
}
} ;
public static void main ( final String[ ] args) throws Exception {
final Scanner sc = new Scanner ( System. in) ;
int n= sc. nextInt ( ) ;
Graph G= new Graph ( n) ;
int m = sc. nextInt ( ) ;
for ( int i = 1 ; i <= m; i++ ) {
int x = sc. nextInt ( ) ;
int y = sc. nextInt ( ) ;
G. addEdge ( x, y) ;
}
G. printGraph ( ) ;
Graph res= G. opst ( ) ;
res. printGraph ( ) ;
}
}