USACO3.2 Sweet Butter(butter)

最短路的題,看上去比較簡單,可是坑爹的超時啊,淚奔了。。。floyd超時,priority_queue沒搞好,最後模仿了一個SPFA算法,纔算是過了。有時間好好研究下這幾種最短路算法。ios

 

/*
ID:jzzlee1
PROB:butter
LANG:C++
*/
//#include<iostream>
#include<fstream>
#include<cstring>
#include<queue>
using namespace std;
ifstream cin("butter.in");
ofstream cout("butter.out");
const int MAX =1000000;
const int pp=801;
int n,p,c;
int cow[pp];
int graph[pp][pp];
int u[3000], v[3000],w[3000],nextt[3000],first[pp],d[pp];
int main()
{
	int i,j,k,e;
    for(i=0;i<pp;i++)
        for(j=0;j<pp;j++)
            graph[i][j]=MAX;
    for(i=0;i<pp;i++)
    {
		first[i]=-1;
		graph[i][i]=0;
	}
    cin>>n>>p>>c;
    int t1,t2,t3;
    for(i=0;i<n;i++)
        cin>>cow[i];
    for(e=0;e<2*c;e++)
    {
        cin>>t1>>t2>>t3;
        u[e]=t1;
		v[e]=t2;
		w[e]=t3;
        nextt[e]=first[u[e]];
        first[u[e]]=e;
        e++;
        u[e]=t2;
		v[e]=t1;
		w[e]=t3;
        nextt[e]=first[u[e]];
        first[u[e]]=e;
    }
    for(k=1;k<=p;k++)
    {
        queue<int> q;
        bool done[pp];
        memset(done,0,sizeof(done));
        for(i=0;i<=p;i++)
            d[i]=(i==k?0:MAX);
        q.push(k);
        while(!q.empty())
        {
            int x=q.front();q.pop();
            done[x]=0;
            for(e=first[x];e!=-1;e=nextt[e])
                if(d[v[e]]>d[x]+w[e])
                {
                    d[v[e]]=d[x]+w[e];
                    if(!done[v[e]])
                    {
                        done[v[e]]=true;
                        q.push(v[e]);
                    }
                }
        }
        for(i=1;i<=p;i++)
			graph[k][i]=d[i]<graph[k][i]?d

[i]:graph[k][i]; 
    }
    for(i=1;i<=p;i++)
		for(j=1;j<=p;j++)
			graph[j][i] = graph[i][j]  ;
    int mini = MAX;
    for(i=1;i<=p;i++)
    {
        int sum = 0;
        for(j=0;j<n;j++)
			sum+=graph[i][cow[j]];
        if(mini>sum)
			mini=sum;
    }
    cout<<mini<<endl;
 return 0;
}
相關文章
相關標籤/搜索