Pagini recente » Cod sursa (job #1130699) | Cod sursa (job #1701895) | Cod sursa (job #2275570) | Cod sursa (job #3341220) | Cod sursa (job #3323506)
#include <bits/stdc++.h>
#include <queue>
#include <fstream>
using namespace std;
int inf = 1e9;
void bellmanford()
{
int n, m;
ifstream fin("bellmanford.in");
ofstream fout("bellamnford.out");
fin >> n >> m;
vector<pair<int, int>> L[n + 1];
vector<int> cnt(n + 1, 0);
vector<long long> dist(n + 1, inf);
queue<int> q;
vector<bool> inQ(n + 1, false);
dist[1] = 0;
inQ[1] = true;
cnt[1] = 1;
q.push(1);
for(int i = 1; i <= m; i ++)
{
int x, y, ct;
fin >> x >> y >> ct;
L[x].push_back({y, ct});
}
int ok = 0;
while(!q.empty())
{
int node = q.front();
q.pop();
inQ[node] = false;
for(auto elem: L[node])
{
int vecin = elem.first;
int cost = elem.second;
if(dist[vecin] > dist[node] + cost)
{ dist[vecin] = dist[node] + cost;
if(inQ[vecin] == false)
{
inQ[vecin] = true;
q.push(vecin);
cnt[vecin] ++;
if(cnt[vecin] > n && !ok) {fout << "Ciclu negativ!"; ok = 1;}
}
}
}
}
if(!ok)
{
for(int i = 2; i <= n ; i++)
{
fout << dist[i] << ' ';
}
}
}
void royfloyd()
{
ifstream fin("royfloyd.in");
ofstream fout("royfloyd.out");
int n;
fin >> n;
long long dist[n + 1][n + 1];
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= n; j ++)
{
dist[i][j] = 1e9;
}
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= n; j ++)
{
int ct;
fin >> ct;
if(ct == 0 && i != j) ct = 1e9;
dist[i][j] = ct;
}
for(int k = 1; k <= n; k ++)
{
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
if(dist[i][j] == 1e9) dist[i][j] = 0;
fout << dist[i][j] << ' ';
}
fout << endl;
}
}
void dijkstra()
{
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n, m;
fin >> n >> m;
priority_queue<pair<int, int>> pq;
vector<long long> dist(n + 1, inf);
vector<pair<int, int>> L[n + 1];
vector<int> vis(n + 1, 0);
for(int i = 1; i <= m; i ++)
{
int x, y, ct;
fin >> x >> y >> ct;
L[x].push_back({y, ct});
//L[y].push_back({x, -ct});
}
dist[1] = 0;
pq.push({-dist[1], 1});
while(!pq.empty())
{
int node = pq.top().second;
pq.pop();
if(vis[node] != 1)
{
vis[node] = 1;
for(auto elem: L[node])
{
int vecin = elem.first;
int cost = elem.second;
if(dist[vecin] > dist[node] + cost)
{
dist[vecin] = dist[node] + cost;
pq.push({-dist[vecin], vecin});
}
}
}
}
for(int d = 2; d <= n; d++)
{
if(vis[d] == 0) dist[d] = 0;
fout << dist[d] << ' ';
}
}
int main()
{
bellmanford();
return 0;
}