这种邻接表的写法哪里错了吗
查看原帖
这种邻接表的写法哪里错了吗
1125894
19859475029l楼主2024/3/12 21:11
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
    static int n,m,idx,res;
    static int N = 2500;
    //    static int[][] local = new int[N][N];//存放点与点之间的位置关系
    static int[] in = new int[N];
    static int[] out = new int[N];
    static int[] f = new int[N];    //存储最长食物链

    static int[] h = new int[N];
    static int[] ne = new int[N];
    static int[] e = new int[N];

    public static void add(int a,int b){
        e[idx] = b;
        ne[idx] = h[a];
        h[a] = idx++;
    }

    public static void main(String[] args) throws IOException {
        Read sc = new Read();
        n = sc.nextInt();
        m = sc.nextInt();

        //初始化邻接表
        for(int i = 1;i <= m;i++){
            int a = sc.nextInt();
            int b = sc.nextInt();
            add(a,b);
            in[b]++;
            out[a]++;
        }


        Queue<Integer> q = new LinkedList<>();
        //将入度为0的点加入队列
        for(int i = 1;i <= n;i++){
            if (in[i] == 0) {
                f[i] = 1;
                q.offer(i);
            }
        }

        while (!q.isEmpty()){
            //取出队头
            int head = q.poll();
            for(int i = h[head];i != 0;i = ne[i]){
                int j = e[i];
                //更新食物链长度和入度
                f[j] += f[head];
                f[j] %= 80112002;
                in[j]--;

                if (in[j] == 0){
                    q.offer(j);
                    if (out[j] == 0){
                        res += f[j];
                        res %= 80112002;
                    }
                }

            }
        }
        System.out.println(res);
    }
}

class Read{
    StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    public int nextInt() throws IOException {
        st.nextToken();
        return (int)st.nval;
    }
}
2024/3/12 21:11
加载中...