Constructing Roads(SPFA+邻接表)

时间:2023-03-09 04:33:42
Constructing Roads(SPFA+邻接表)

题目描述

Long long ago, There was a country named X, the country has N cities which are numbered from 1 to N.
    The king of Country-X wants to construct some roads.
    Please note that Country-X is blessed by an angel. He(The angel is a boy? This is no science, but do not care about those details, this angel is so cute, he must be a boy) can use magic to make one road connections directly from two cities’ cost to be half, but the magic can only be used once.
    The king wants to know the minimal cost to construct a road between City-A and City-B. Because of there are so many cities and roads, the construction division comes to you, the only programmer he knows, for help.
You should write a program to calculate the minimal cost between City-A and City-B to help him.

输入

    There are multiple test cases.
    For each test case:
    The fist line is two integers N and M (2 <= N <= 1000,0 <= M <= 50000). 
    Each of the following M lines contains three integers U、V and W (1<= U,V<= N, 0 <= W <= 1000) . It shows that if we construct a road between the U-th city and the V-th city , the cost is W.
    The next line is two integers A and B (1<= A, B <= N).

输出

    For each test case,output one line containing the minimal cost , if there is no route from A to B , the output should contain the string “No solution” (without the quotes).

示例输入

2 1
1 2 99
1 2
4 3
1 2 312
2 3 520
3 1 999
3 4

示例输出

49
No solution 题意:给m条边,求出s到t的最短路径,其中有一条边的权值可以减半。
思路:两次SPFA,再穷举每一条边,让其减半,最后比较得住最小权值。
 #include<stdio.h>
#include<string.h>
#include<queue>
using namespace std; const int maxn = ;
const int INF = 0x3f3f3f3f;
struct node
{
int u,v,w;
int next;
}edge[];
int n,m,cnt;
int p[];
int dis[][maxn];//dis[0][i]表示起点到所有点的最短路,dis[1][i]表示终点到所有点的最短路。
int inque[maxn]; void add(int u, int v, int w)
{
edge[cnt].u = u;
edge[cnt].v = v;
edge[cnt].w = w;
edge[cnt].next = p[u];
p[u] = cnt;
cnt++;
}
void spfa(int s, int f)
{
queue<int>que;
while(!que.empty())
que.pop();
memset(inque,,sizeof(inque));
for(int i = ; i <= n; i++)
dis[f][i] = INF; que.push(s);
inque[s] = ;
dis[f][s] = ; while(!que.empty())
{
int u = que.front();
que.pop();
inque[u] = ; for(int i = p[u]; i; i = edge[i].next)
{
if(dis[f][edge[i].v] > dis[f][u] + edge[i].w)
{
dis[f][edge[i].v] = dis[f][u] + edge[i].w;
if(!inque[edge[i].v])
{
inque[edge[i].v] = ;
que.push(edge[i].v);
}
}
}
}
} int main()
{
//freopen("data1.in","r",stdin);
//freopen("c.txt","w",stdout);
while(~scanf("%d %d",&n,&m))
{
int u,v,w;
cnt = ;
memset(p,,sizeof(p));//前项星
for(int i = ; i < m; i++)
{
scanf("%d %d %d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
int s,t;
scanf("%d %d",&s,&t);
spfa(s,);
spfa(t,);
int ans = INF;
for(int i = ; i < cnt; i++)
{
u = edge[i].u;
v = edge[i].v;
w = edge[i].w;
int d = dis[][u] + dis[][v] + w/;
if(ans > d)
ans = d;
}
if(ans >= INF)
printf("No solution\n");
else printf("%d\n",ans);
}
return ;
}