Pagini recente » Cod sursa (job #2688483) | Cod sursa (job #2983335) | Cod sursa (job #2178452) | Cod sursa (job #2546034) | Cod sursa (job #365139)
Cod sursa(job #365139)
#include <fstream>
#include <iostream>
using namespace std;
struct nod{
int capat, cost;
nod *next;
};
nod * a[30001];
int n, x , y ;
void read(){
int m ;
ifstream fin("sate.in");
fin>>n>>m>>x>>y;
for(int i=1;i<=n ;i++)
a[i]= NULL;
int i,j,c;
for( ; m ; m--){
fin >> i >> j >> c;
nod * tmp = new nod;
tmp->capat= j;
tmp->cost= c;
tmp->next = a[i];
a[i] = tmp;
tmp = new nod ;
tmp -> capat = i;
tmp -> cost = c;
tmp -> next = a[j];
a[j] = tmp;
}
fin.close();
}
void write(){
for(int i =1 ;i<= n;i++){
nod * p = a[i];
cout<<i<<" : ";
for(; p; p=p->next)
cout<<p->capat<<" ";
cout<<endl;
}
}
int bfs(int x, int y){
int coada [30001], st=1,dr=1, v[30001],cost[30001];
for(int i =1 ;i<=n;i++)
v[i]=cost[i]=0;
coada[1]=x;
v[x]=1;
while(st<=dr){
int k = coada[st++];
for(nod * p=a[k] ; p ; p = p->next)
if( v[p->capat] == 0 ){
int j = p->capat, c = p->cost;
coada[++dr] = j;
v[j] = 1;
if(k<j)
cost[j] = cost[k] + c;
else
cost[j] = cost[k] - c;
if(j == y){
//for(int i=1 ; i <= dr;i++)
// cout<<coada[i]<<" ";
//cout<<endl;
return cost[j];
}
}
}
return -1;
}
int sol(int x, int y){
if(x==y)
return 0;
if(x>y)
return bfs(y,x);
else
return bfs(x,y);
}
int main(){
read();
// cout<<x<<" "<<y<<" "<<sol(x,y);
// write();
ofstream fout("sate.out");
fout<<sol(x,y);
fout.close();
return 0;
}