1. 有向图中反向图构造。对tinyDG.txt(http://pan.baidu.com/s/1o6jWtcA)文件所表示的图,输出其邻接表表示 与 反向图的邻接表表示。
邻接表表示示例如下:
0:1 5
1:
2:0 3
……
程序思路:由于邻接表的表示方式和二维数组有一点相似,所以我才用的是用一个数组类和list接口来表示出类似二维数组的效果。
实现代码:
import java.io.*;
import java.util.*;
public class GraphReverse
{
public static void main(String[] args)
{
try
{
FileReader fr=new FileReader("d:\\1\\123.txt");
BufferedReader br=new BufferedReader(fr);
int v,e;
String str="",str1="";
str=br.readLine();
v=Integer.parseInt(str);
System.out.println(v);
str="";
str=br.readLine();
e=Integer.parseInt(str);
System.out.println(e);
int a,b;
// List list=new ArrayList();
ll[] arr=new ll[v];
ll[] arr1=new ll[v];
for(a=0;a<v;a++)
{
arr[a]=new ll();
arr1[a]=new ll();
}
str="";
int t1;
while((t1=br.read())!=-1)
{
str = str + (char) t1;
if((char)t1==' ')
{
a = Integer.parseInt(str.trim());
str="";
}
if((char)t1=='\n')
{
b = Integer.parseInt(str.trim());
arr[a].add(b);
arr1[b].add(a);
str="";
}
}
br.close();
fr.close();
FileOutputStream fos = new FileOutputStream("d:\\1\\234.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "gb2312");
BufferedWriter bw = new BufferedWriter(osw);
FileOutputStream fos1 = new FileOutputStream("d:\\1\\345.txt");
OutputStreamWriter osw1 = new OutputStreamWriter(fos1, "gb2312");
BufferedWriter bw1 = new BufferedWriter(osw1);
for(a=0;a<v;a++)
{
System.out.print(a+": ");
for(b=0;b<arr[a].size();b++)
{
System.out.print(arr[a].get(b)+" ");
str=str+Integer.toString(arr[a].get(b))+" ";
}
System.out.println();
str=Integer.toString(a)+": "+str;
bw.write(str);
bw.newLine();
str="";
}
System.out.println();
System.out.println();
str="";
for(a=0;a<v;a++)
{
System.out.print(a+": ");
for(b=0;b<arr1[a].size();b++)
{
System.out.print(arr1[a].get(b)+" ");
str=str+Integer.toString(arr1[a].get(b))+" ";
}
System.out.println();
str=Integer.toString(a)+": "+str;
bw1.write(str);
bw1.newLine();
str="";
}
bw.close();
osw.close();
bw1.close();
osw1.close();
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class ll
{
private List list=new ArrayList();
public void add(int a)
{
list.add(a);
}
public int size()
{
return list.size();
}
public int get(int c)
{
return Integer.parseInt(list.get(c).toString());//object类型转为int
}
}
运行结果: