luogu P1346 电车 基础最短路径dijkstra+堆优化 板子题

题目描述

在一个神奇的小镇上有着一个特别的电车网络,它由一些路口和轨道组成,每个路口都连接着若干个轨道,每个轨道都通向一个路口(不排除有的观光轨道转一圈后返回路口的可能)。在每个路口,都有一个开关决定着出去的轨道,每个开关都有一个默认的状态,每辆电车行驶到路口之后,只能从开关所指向的轨道出去,如果电车司机想走另一个轨道,他就必须下车切换开关的状态。

为了行驶向目标地点,电车司机不得不经常下车来切换开关,于是,他们想请你写一个程序,计算一辆从路口 AAA 到路口 BBB 最少需要下车切换几次开关。
输入格式

第一行有 333 个整数 N,A,BN,A,BN,A,B(2≤N≤100,1≤A,B≤N2 \leq N \leq 100, 1 \leq A,B \leq N2≤N≤100,1≤A,B≤N),分别表示路口的数量,和电车的起点,终点。

接下来有 NNN 行,每行的开头有一个数字 KiK_iKi​(0≤Ki≤N−10 \leq K_i \leq N-10≤Ki​≤N−1),表示这个路口与 KiK_iKi​ 条轨道相连,接下来有 KiK_iKi​ 个数字表示每条轨道所通向的路口,开关默认指向第一个数字表示的轨道。
输出格式

输出文件只有一个数字,表示从 AAA 到 BBB 所需的最少的切换开关次数,若无法从 AAA 前往 BBB,输出 −1-1−1。
输入输出样例
输入 #1

3 2 1
2 2 3
2 3 1
2 1 2

输出 #1

0



题意 :给定一张图,一个节点U与第一个相连的点V1边权为0
与其他相连的点边权为1,求最短路。(老实说没看懂题意,看别人的题解是这么说的) 囧

  • 建图,跑迪杰斯特拉+堆优化即可

c++代码

// #define debug
#ifdef debug
#include 
#include "win_majiao.h"
#endif

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define MAXN ((int)1e5+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)

using namespace std;
typedef vector<vector<int> > VVI;

#define show(x...) \
	do { \
		cout << "\033[31;1m " << #x << " -> "; \
		err(x); \
	} while (0)

void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }

namespace FastIO{

	char print_f[105];
	void read() {}
	void print() { putchar('\n'); }

	template <typename T, typename... T2>
	   inline void read(T &x, T2 &... oth) {
		   x = 0;
		   char ch = getchar();
		   ll f = 1;
		   while (!isdigit(ch)) {
			   if (ch == '-') f *= -1; 
			   ch = getchar();
		   }
		   while (isdigit(ch)) {
			   x = x * 10 + ch - 48;
			   ch = getchar();
		   }
		   x *= f;
		   read(oth...);
	   }
	template <typename T, typename... T2>
	   inline void print(T x, T2... oth) {
		   ll p3=-1;
		   if(x<0) putchar('-'), x=-x;
		   do{
				print_f[++p3] = x%10 + 48;
		   } while(x/=10);
		   while(p3>=0) putchar(print_f[p3--]);
		   putchar(' ');
		   print(oth...);
	   }
} // namespace FastIO
using FastIO::print;
using FastIO::read;

int n, m, Q, K, S, E;

bool vis[MAXN];
int d[MAXN], sum[MAXN];
vector<pair<int, int> > G[MAXN];

int dij() {
	priority_queue<pair<int,int> > q;
	memset(d, INF, sizeof(d));
	memset(sum, 0, sizeof(sum));
	q.push({-d[S], S});
	d[S] = 0;

	while(!q.empty()) {
		auto now = q.top(); q.pop();
		int u = now.second;
		// show(u);
		for(auto ed : G[u]) {
			int v = ed.first, td = ed.second;
			// show(u, v, td, d[u], d[v]);
			if(d[v] > d[u] + td) {
				d[v] = d[u] + td;
				q.push({-d[v], v});
			}
		}
	}
	return d[E];
}

signed main() {
#ifdef debug
	freopen("test.txt", "r", stdin);
	clock_t stime = clock();
#endif

	read(n, S, E);
	for(int i=1; i<=n; i++) {
		read(K);
		int u = i, v = 0;
		for(int j=0; j<K; j++) {
			read(v);
			G[u].push_back({v, (j>0)});
			// G[v].push_back({u, (j>0)});
		}
	}
	int ans = dij();
	printf("%d\n", ans == INF ? -1 : ans);




#ifdef debug
	clock_t etime = clock();
	printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif 
	return 0;
}



java代码





import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

public class Main {
    public static final boolean debug = false;
    public static String INPATH = "C:\\Users\\majiao\\Desktop\\test.txt",
            OUTPATH = "C:\\Users\\majiao\\Desktop\\out.txt";
    public static StreamTokenizer tok;
    public static BufferedReader cin;
    public static PrintWriter cout;

    public static long start_time = 0, out_time = 0;
    public static int n, m, K, Q, MAXN = (int)1e5+7, INF = 0x3f3f3f3f,
            pre[] = new int[MAXN], sum[] = new int[MAXN], POS = 50000;
    public static byte buf[] = new byte[MAXN];

    public static int fa(int x) { return pre[x]==x ? x : (pre[x]=fa(pre[x])); }

    public static void union_xy(int x, int y) {
        x = fa(x); y = fa(y);
        if(x != y) {
            sum[x] += sum[y];
            pre[y] = x;
        }
    }

    public static int d[] = new int[MAXN];
    public static List<Pair> G[] = new ArrayList[MAXN];

    public static int dij(int S, int E) {
        Arrays.fill(d, INF);
        d[S] = 0;
        PriorityQueue<Pair> q = new PriorityQueue<>();
        q.add(new Pair(-d[S], S));
        while(!q.isEmpty()) {
            Pair now = q.poll();
            int u = now.sec;
            for (Pair ed : G[u]) {
                int v = ed.fst, td = ed.sec;
                if(d[v] > d[u] + td) {
                    d[v] = d[u] + td;
                    q.add(new Pair(-d[v], v));
                }
            }
        }
        return d[E];
    }

    public static void main(String[] args) throws IOException {
        main_init();
        if(debug) { start_time = System.currentTimeMillis(); }
        if(false) { System.setOut(new PrintStream(OUTPATH)); }

        n = read_int();
        int S = read_int();
        int E = read_int();
        for(int i=1; i<=n; i++) {
            G[i] = new ArrayList<>();
            K = read_int();
            int u = i, v, w;
            for(int j=0; j<K; j++) {
                v = read_int();
                w = j > 0 ? 1 : 0;
                G[u].add(new Pair(v, w));
            }
        }
        int ans = dij(S, E);
        cout.printf("%d\n", ans == INF ? -1 : ans);










        if(debug) {
            out_time = System.currentTimeMillis();
            cout.printf("run time : %d ms\n", out_time-start_time);
        }
        cout.flush();
    }

    public static void show(List<Object> list, Object... obj) {
        cout.printf("%s : ", obj.length>0 ? obj[0] : "");
        for(Object x : list) {
            cout.printf("[%s] ", x);
        }
        cout.printf("\n");
    }

    public static void show(Map<Object, Object> mp, Object... obj) {
        cout.printf("%s : ", obj.length>0 ? obj[0] : "");
        Set<Map.Entry<Object, Object>> entries = mp.entrySet();
        for (Map.Entry<Object, Object> en : entries) {
            cout.printf("[%s,%s] ", en.getKey(), en.getValue());
        }
        cout.printf("\n");
    }

    public static<T> void forarr(int[] d, int... args) {
        int lef = 0, rig = d.length - 1;
        if(args.length > 0) { lef = args[0]; rig = args[1]; }
        cout.printf(" : ");
        for( ; lef<=rig; lef++) {
            cout.printf("[%s] ", args[lef]);
        }
        cout.printf("\n");
    }

    public static void main_init() {
        try {
            if (debug) {
                cin = new BufferedReader(new InputStreamReader(
                        new FileInputStream(INPATH)));
            } else {
                cin = new BufferedReader(new InputStreamReader(System.in));
            }
            cout = new PrintWriter(new OutputStreamWriter(System.out));
//            cout = new PrintWriter(OUTPATH);
            tok = new StreamTokenizer(cin);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String next_str() {
        try {
            tok.nextToken();
            if (tok.ttype == StreamTokenizer.TT_EOF)
                return null;
            else if (tok.ttype == StreamTokenizer.TT_NUMBER) {
                return String.valueOf((int)tok.nval);
            } else if (tok.ttype == StreamTokenizer.TT_WORD) {
                return tok.sval;
            } else return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static int read_int() {
        String tmp_next_str = next_str();
        return null==tmp_next_str ? -1 : Integer.parseInt(tmp_next_str);
    }
    public static long read_long() { return Long.parseLong(next_str()); }
    public static double read_double() { return Double.parseDouble(next_str()); }
    public static BigInteger read_big() { return new BigInteger(next_str()); }
    public static BigDecimal read_dec() { return new BigDecimal(next_str()); }


    static class Edge implements Comparable<Edge> {
        int u, v, w;
        @Override
        public int compareTo(Edge o) { return w - o.w; }
    }
    static Edge a[] = new Edge[MAXN];

    static class Pair implements Comparable<Pair>{
        int fst, sec;
        public Pair() { }
        public Pair(int fst, int sec) {
            this.fst = fst;
            this.sec = sec;
        }
        @Override
        public int compareTo(Pair o) {
            return fst - o.fst == 0 ? sec - o.sec : fst - o.fst;
        }
    }
}

你可能感兴趣的:(迪杰斯特拉最短路堆优化,板子题,看不懂题意,语文题)