BestCoder Round #53 (div.2) HDOJ5422 Rikka with Graph(floyd)

本文介绍了解决特定数学问题的方法,即在无向图中添加一条边以最小化从顶点1到顶点n的最短路径,并计算可能的方案数量。通过使用Floyd算法解决最短路径问题,文章提供了详细的输入输出格式说明及AC代码解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Rikka with Graph

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 232    Accepted Submission(s): 124


Problem Description
As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:

Yuta has a non-direct graph with n vertices and m edges. The length of each edge is 1. Now he wants to add exactly an edge which connects two different vertices and minimize the length of the shortest path between vertice 1 and vertice n. Now he wants to know the minimal length of the shortest path and the number of the ways of adding this edge.

It is too difficult for Rikka. Can you help her?
 

Input
There are no more than 100 testcases. 

For each testcase, the first line contains two numbers n,m(2n100,0m100).

Then m lines follow. Each line contains two numbers u,v(1u,vn) , which means there is an edge between u and v. There may be multiedges and self loops.
 

Output
For each testcase, print a single line contains two numbers: The length of the shortest path between vertice 1 and vertice n and the number of the ways of adding this edge.
 

Sample Input
2 1 1 2
 

Sample Output
1 1
Hint
You can only add an edge between 1 and 2.
 



如果1-n已经连接了,那么最短路是1,随便连一条边即可,方案数为n * (n - 1) / 2。

如果1-n还没有连接,那么要保证最短只能连接1-n,方案数为1。


AC代码:


#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 105;
const int INF = 0x3f3f3f3f;
int n, m, map[MAXN][MAXN];
void floyd()
{
	for(int k = 1; k <= n; ++k)
		for(int i = 1; i <= n; ++i)
			for(int j = 1; j <= n; ++j)
				if(map[i][k] + map[k][j] < map[i][j])
					map[i][j] = map[i][k] + map[k][j];
}
int main(int argc, char const *argv[])
{
	while(scanf("%d%d", &n, &m) != EOF) {
		memset(map, INF, sizeof(map));
		for(int i = 0; i <= n; ++i)
			map[i][i] = 1;
		for(int i = 0; i < m; ++i) {
			int x, y;
			scanf("%d%d", &x, &y);
			map[x][y] = map[y][x] = 1;
		}
		floyd();
		if(map[1][n] == 1) printf("1 %d\n", n * (n - 1) / 2);
		else printf("1 1\n");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值