HHUOJ 1019 Friendship of Mouse(水题)

本文介绍了一道关于寻找来自同一城市且站立位置最近的老鼠对的算法题。通过给出的示例和代码,展示了如何计算任意两个来自相同城市的相邻老鼠之间的最小距离。

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

问题 B: Friendship of Mouse

时间限制: 1 Sec  内存限制: 64 MB
提交: 10  解决: 7


题目描述

Today in KBW, N mice from different cities are standing in a line. Each city is represented by a lowercase letter. The distance between adjacent mice (e.g. the 1st and the 2nd mouse, the N−1th and the Nth mouse, etc) are exactly 1. Two mice are friends if they come from the same city.

The closest friends are a pair of friends with the minimum distance. Help us find that distance.

输入

First line contains an integer T, which indicates the number of test cases.

Every test case only contains a string with length N, and the ith character of the string indicates the city of ith mice.

⋅ 1≤T≤50.

⋅ for 80% data, 1≤N≤100.

⋅ for 100% data, 1≤N≤1000.

⋅ the string only contains lowercase letters.

输出

For every test case, you should output "Case #x: y", where x indicates the case number and counts from 1 and y is the result. If there are no mice in same city, output −1 instead.

样例输入

2
abcecba
abc

样例输出

Case #1: 2
Case #2: -1


思路:

2015 ICPC 上海站F题,很水的一道打卡题,怎么做都行,N^2暴力都无所谓...

代码:

#include<iostream> 
#include <cstdio>
#include <cstring>
#include <algorithm>
#define maxn 1005
#define inf 99999
using namespace std;

char str[maxn];

int main () 
{
	//freopen("in.txt","r",stdin);
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) 
	{
        scanf("%s", str);
        int len = strlen(str);
		int ans = 99999;
        for (int q = 0; q < len; q++)
            for (int w = q + 1; w < len; w++) 
			{
				if (str[q] == str[w])
                ans = min(ans, w - q);
			}
        if (ans == inf) ans = -1;
        printf("Case #%d: %d\n", i, ans);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值