Pagini recente » Cod sursa (job #865529) | Cod sursa (job #1422564) | Cod sursa (job #2253491) | Cod sursa (job #2138079) | Cod sursa (job #2191189)
//Dijkstra O(n^2 + m) = O(n^2)
#include<cstdio>
#include<vector>
#include<cctype>
#define MAX_N 50000
#define BUF_SIZE 1 << 18
#define oo 0x3f3f3f3f
using namespace std;
vector<pair<int,int> >g[MAX_N + 1];
int dist[MAX_N + 1], n, m, pos = BUF_SIZE;
bool used[MAX_N + 1];
char buf[BUF_SIZE];
char getChar(FILE* fin) {
if(pos == BUF_SIZE) {
fread(buf,1,BUF_SIZE,fin);
pos = 0;
}
return buf[pos++];
}
int read(FILE *fin) {
int res = 0;
char c;
do {
c = getChar(fin);
}while(!isdigit(c));
do {
res = 10*res + c - '0';
c = getChar(fin);
}while(isdigit(c));
return res;
}
void readGraph() {
int x, y, cost;
FILE* fin = fopen("dijkstra.in","r");
n = read(fin);
m = read(fin);
for(int i = 0; i < m; i++) {
x = read(fin);
y = read(fin);
cost = read(fin);
g[x].push_back(make_pair(y,cost));
}
fclose(fin);
}
void Dijkstra(int node) {
vector<pair<int,int> >::iterator it;
int i, j, minNode;
for(i = 0; i <= n; i++)
dist[i] = oo;
dist[node] = 0;
for(i = 1; i <= n; i++) {
minNode = 0;
for(j = 1; j <= n; j++)
if(!used[j] && dist[j] < dist[minNode])
minNode = j;
used[minNode] = true;
for(it = g[minNode].begin(); it != g[minNode].end(); it++)
if(dist[(*it).first] > dist[minNode] + (*it).second)
dist[(*it).first] = dist[minNode] + (*it).second;
}
}
void printDistances() {
FILE* fout = fopen("dijkstra.out","w");
for(int i = 2; i <= n; i++)
if(dist[i] != oo)
fprintf(fout,"%d ",dist[i]);
else fprintf(fout,"0 ");
fprintf(fout,"\n");
fclose(fout);
}
int main() {
readGraph();
Dijkstra(1);
printDistances();
return 0;
}