只有三十分,不知道哪里错了
查看原帖
只有三十分,不知道哪里错了
1140371
ruanertanjing楼主2024/4/11 12:48
//P5767 [NOI1997] 最优乘车
//https://www.luogu.com.cn/problem/P5767



#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <deque>
#include <functional>
#include <climits>
#include <cstring>

#define quickio ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
#define endl "\n"

using namespace std;
typedef long long ll;

const int N = 50005;
const int M = 50005;

int head[N];
int cnt;
int vis[N];
int ans[N];
int n, m;

struct EDGE
{
	int v;
	int w;
	int next;
}EDGE[M];

void add(int u, int v, int w)
{
	cnt++;
	EDGE[cnt].v = v;
	EDGE[cnt].w = w;
	EDGE[cnt].next = head[u];
	head[u] = cnt;
}

void Dij(int s)
{
	priority_queue<pair<int, int> >que;
	que.push({ 0, s });
	ans[s] = 0;

	while (!que.empty())
	{
		int dis = -que.top().first;
		int dian = que.top().second;
		que.pop();

		if (dis !=ans[dian])
			continue;
		if (vis[dian] == 0)
		{
			for (int j = head[dian]; j; j = EDGE[j].next)
			{
				int t = EDGE[j].v;
				int w = EDGE[j].w;
				if (ans[t] > w + ans[dian])
				{
					ans[t] = w + ans[dian];
					if (vis[t] == 0)
						que.push({ -ans[t], t });
				}
			}
		}
	}
}

int main()
{
	cin >> m >> n;
	int u, v;
	int arr[505] = { 0 };
	getchar();//把上一行的换行符读了
	for (int i = 0; i < m; i++)
	{
		string temp;
		getline(cin, temp);//要包含<string>头文件,而不是<cstring>
		int flag = 0;
		for (int j = 0; j < temp.size(); j++)
		{
			if (temp[j] >= '0' && temp[j] <= '9')
			{
				arr[flag++] = temp[j] - '0';
			}
		}

		for (int j = 0; j < flag - 1; j++)
		{
			for (int k = j + 1; k < flag; k++)
			{
				u = arr[j];
				v = arr[k];
				add(u, v, 1);//注意是单向边
			}
		}
	}

	memset(ans, 0x3f, sizeof(ans));/**/
	Dij(1);
	if (ans[n] == 0x3f3f3f3f)
		cout << "NO" << endl;
	else
		cout << ans[n] - 1 << endl;

	return 0;
}
2024/4/11 12:48
加载中...