#include <iostream> #include <cstring> using namespace std; const int N = 1000010; int n, m, s, t; bool st[N]; int h[N], e[N], w[N], ne[N], idx; int d[N]; void add(int u, int v, int weight) { e[idx] = v, w[idx] = weight, ne[idx] = h[u], h[u] = idx ++; } int dijkstra() { memset(d, 0x3f, sizeof d); d[s] = 0; for (int i = 0; i < n; i ++ ) { int t = -1; for (int j = 1; j <= n; j ++ ) if (!st[j] && (t == -1 || d[t] > d[j])) t = j; st[t] = true; for (int j = h[t]; j != -1; j = ne[j]) { int k = e[j]; if (d[k] > d[t] + w[j]) d[k] = d[t] + w[j]; } } return d[t]; } int main() { cin >> n >> m >> s >> t; memset(h, -1, sizeof h); while (m -- ) { int u, v, weight; cin >> u >> v >> weight; add(u, v, weight); add(v, u, weight); } cout << dijkstra() << endl; return 0; }这段代码用scanf替代cin
时间: 2024-01-20 12:02:38 浏览: 100
您使用scanf来替代cin,以下是修改后的代码示例:
```c++
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1000010;
int n, m, s, t;
bool st[N];
int h[N], e[N], w[N], ne[N], idx;
int d[N];
void add(int u, int v, int weight)
{
e[idx] = v, w[idx] = weight, ne[idx] = h[u], h[u] = idx ++;
}
int dijkstra()
{
memset(d, 0x3f, sizeof d);
d[s] = 0;
for (int i = 0; i < n; i ++ )
{
int t = -1;
for (int j = 1; j <= n; j ++ )
if (!st[j] && (t == -1 || d[t] > d[j]))
t = j;
st[t] = true;
for (int j = h[t]; j != -1; j = ne[j])
{
int k = e[j];
if (d[k] > d[t] + w[j])
d[k] = d[t] + w[j];
}
}
return d[t];
}
int main()
{
scanf("%d%d%d%d", &n, &m, &s, &t);
memset(h, -1, sizeof h);
while (m -- )
{
int u, v, weight;
scanf("%d%d%d", &u, &v, &weight);
add(u, v, weight);
add(v, u, weight);
}
printf("%d\n", dijkstra());
return 0;
}
```
注意,scanf函数的用法与cin不同,需要指定输入的变量类型,并且需要使用&符号获取变量的地址。另外,输出时需要使用printf函数。
阅读全文