给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,
如果最短距离有多条路线,则输出花费最少的。
输入:
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。
最后一行是两个数 s,t;起点s,终点t。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
输出:
输出 一行有两个数, 最短距离及其花费。
样例输入:
3 2
1 2 5 6
2 3 4 5
1 3
0 0
样例输出:
9 11
来源:
如果最短距离有多条路线,则输出花费最少的。
输入:
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。
最后一行是两个数 s,t;起点s,终点t。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
输出:
输出 一行有两个数, 最短距离及其花费。
样例输入:
3 2
1 2 5 6
2 3 4 5
1 3
0 0
样例输出:
9 11
来源:
2010年浙江大学计算机及软件工程研究生机试真题
//1最短距离
//2相同距离最少花费
#include<stdio.h>
#include<vector>
using namespace std;
struct E
{
int next;//next node
int c;//distance
int cost;//cost
};
vector < E > edge[1001];//邻接链表
int Dis[1001];
int cost[1001];
bool mark[1001];
//DJS 选取集合体的最小距离
int main()
{
int n,m,i,j;
int S,T;//beginning,ending
while(~scanf("%d %d",&n,&m))//n node,m edge without direction
{
if(0==n&&0==m)break;
for(i=1;i<=n;i++)edge[i].clear();
while(m--)
{
int a,b,c,cost;
scanf("%d %d %d %d",&a,&b,&c,&cost);//nodeA nodeB length cost
E tmp;
tmp.c=c;
tmp.cost=cost;
tmp.next=b;
edge[a].push_back(tmp);//edge start with a,link a to b
tmp.next=a;
edge[b].push_back(tmp);
}
scanf("%d %d",&S,&T);
for(i=1;i<=n;i++)//initiate
{
Dis[i]=-1;
mark[i]=false;
}
Dis[S]=0;
mark[S]=true;
int newP=S;
for(i=1;i<n;i++)
{
//测试每个集合体中节点到其他节点的最短距离
for(j=0;j<edge[newP].size();j++)
//j is just a counter,the edge start with newP,edge[newP],edge[newP][j] represents the starting node and the NO.j edge
{
int t=edge[newP][j].next;//edge[newP][j].next Node newP---Edge edge[newP][j]---Node edge[newP][j].next
int c=edge[newP][j].c;//distance
int co=edge[newP][j].cost;//cost
if(true==mark[t])continue;
//condition 3:same distance,less cost
if(Dis[t]==-1||Dis[t]>Dis[newP]+c||Dis[t]==Dis[newP]+c&&cost[t]>cost[newP]+co)
{
Dis[t]=Dis[newP]+c;
cost[t]=cost[newP]+co;
}
}
int min=123123123;
//选取连接集合体的最短距离
for(j=1;j<=n;j++)
{
if(true==mark[j])continue;//have been connected
if(-1==Dis[j])continue;//can't connect
if(Dis[j]<min)//beat,get first
{
min=Dis[j];
newP=j;
}
}
mark[newP]=true;
}
printf("%d %d\n",Dis[T],cost[T]);
}
return 0;
}