Cod sursa(job #1112165)

Utilizator span7aRazvan span7a Data 19 februarie 2014 15:13:49
Problema Ubuntzei Scor 45
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.87 kb
#include<fstream>
#define M 2000000000
using namespace std;
ifstream f("ubuntzei.in");
ofstream g("ubuntzei.out");
 
struct nod
{
    int inf;
    int c;
    nod * leg;
};
typedef nod* PNod;
PNod L[2001];
int q[800000],cost[2001],n,m,x,y,s,v[16],a[2001][2001],cmin=M,k;
void add(int a,int b,int costi)
{
    PNod p=new nod;
    p->inf=b;
    p->c=costi;
    p->leg=L[a];
    L[a]=p;
}
void bellford(int poz)
{	 int i;
	q[1]=poz; 
	for(i=1;i<=n;i++)
            cost[i]=M;
	cost[poz]=0;
     int inc=1,sf=1,ok=0;
    while(inc<=sf&&ok==0)
    {
        for(PNod p=L[q[inc]];p;p=p->leg)
            if(cost[p->inf]>cost[q[inc]]+p->c)
            {
                cost[p->inf]=cost[q[inc]]+p->c;
                sf++;
                q[sf]=p->inf;
                  
 
            }
        inc++;
    }
  
	
 
}
int viz[2001],x1[2001];
void solve()
{
    int ctot=a[1][v[x1[1]]];
    for(int i=1;i<=k;i++)
        ctot+=a[v[x1[i-1]]][v[x1[i]]];
    cmin=min(cmin,ctot+a[v[x1[k]]][n]);
}
 
void back(int j)
{
    if(j>k)
        solve();
    else for(int i=1;i<=k;i++)
        if(!viz[i])
        {
            viz[i]=1;
            x1[j]=i;
            back(j+1);
            viz[i]=0;
        }
}
int main()
{
    int a1,b,costi,i;
    f>>n>>m;
    
	f>>k;
	for(i=1;i<=k;i++)
		f>>v[i];
		for(i=1;i<=m;i++)
      {
		  
           f>>a1>>b>>costi;
		  
        add(a1,b,costi);add(b,a1,costi);
      }
	if(k==0){ bellford(1);g<<cost[n];return 0;}		
	if(k==1){bellford(1);s+=cost[v[1]];bellford(v[1]);s+=cost[n];g<<s;return 0;}

		
		bellford(1);
		for(i=1;i<=n;i++){
			a[1][i]=cost[i];
			
		}
		a[1][1]=M;
		for(i=1;i<=k;i++)
		{	
			
			bellford(v[i]);
			for(int i1=1;i1<=n;i1++)
				{
					a[v[i]][i1]=cost[i1];	
				}	
	a[v[i]][v[i]]=M;			
			
		}
		back(1);	
				
        g<<cmin;

    return 0;
}