using namespace std;
int graph[601][601];
int floyd(int n) {
for (int i = 1; i < n; i++)
for (int j = 1; j < n; j++)
graph[0][j] = graph[0][j] < graph[i][j] + graph[0][i] ? graph[0][j] : graph[0][i] + graph[i][j];
return graph[0][n - 1];
}
int main() {
int n, x;
cin >> n >> x;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j)graph[i][j] = MAX;
}
}
for (int i = 0; i < x; i++) {
int a, b, w;
cin >> a >> b >> w;
graph[a - 1][b - 1] = w;
}
int result = floyd(n);
cout << ((result<MAX)?result:-1) << endl;
return 0;
}
这道题WA了十几次,然后发现因为是有向图我当成无向图去做了
include
using namespace std;
define max 1e6
int s[600][600]={0};
bool visit[600]={false};
int main(){
for(int i=0;i<600;i++)
for(int j=0;j<600;j++)
s[i][j]=max;
int n,m;
cin>>n>>m;
for(int i=0;i>temp1>>temp2>>temp3;
s[temp1][temp2]=temp3;
}
for(int i=2;i<=n;i++){
int min=max,temp;
for(int j=1;j<=n;j++)
if(!visit[j]&&s[1][j]<min){
min=s[1][j];
temp=j;
}
visit[temp]=true;
for(int j=1;j<=n;j++)
if(!visit[j]&&s[1][temp]+s[temp][j]<s[1][j])
s[1][j]=s[1][temp]+s[temp][j];
}
if(s[1][n]==max)
cout<<”-1”<<endl;
else
cout<<s[1][n]<<endl;
return 0;
}
只会用书上的方法……
完全抄书……就是那个最大值需要定的大一点嗯
include
include
include
define MAXINT 9999999
define MAXN 1800
typedef int MAT[MAXN][MAXN];
MAT cost;
int dist[MAXN];int pre[MAXN];int n,v;
void shortestpath(MAT cost,int n,int v,int dist[],int pre[])
{
int s[MAXN],j,k,i,min;
for(i=1;i<=n;i++)
{
dist[i]=cost[v][i];
s[i]=0;
if(dist[i]<MAXINT)
pre[i]=v;
else pre[i]=0; //初始化pre数组
if(dist[n]<MAXINT) printf(“%d\n”,dist[n]);
else printf(“-1\n”);
}
int main()
{
int m;int i;
int u1,v1,w;
scanf(“%d%d”,&n,&m);
memset(cost,MAXINT,sizeof(cost));
for(i=1;i<=m;i++)
{
scanf(“%d%d%d”,&u1,&v1,&w);
cost[u1][v1]=w;
}
for(i=1;i<=n;i++)
{
cost[i][i]=0;
}
shortestpath(cost,n,1,dist,pre);
return 0;
}
include
define MAX 0xffff
using namespace std;
int graph[601][601];
int floyd(int n) {
for (int i = 1; i < n; i++)
for (int j = 1; j < n; j++)
graph[0][j] = graph[0][j] < graph[i][j] + graph[0][i] ? graph[0][j] : graph[0][i] + graph[i][j];
return graph[0][n - 1];
}
int main() {
int n, x;
cin >> n >> x;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j)graph[i][j] = MAX;
}
}
for (int i = 0; i < x; i++) {
int a, b, w;
cin >> a >> b >> w;
graph[a - 1][b - 1] = w;
}
int result = floyd(n);
cout << ((result<MAX)?result:-1) << endl;
return 0;
}