跳到正文

题解

UVA12918 题解

ikunTLE约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年12月21日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 2 分钟
获赞
11
题目
UVA12918

版本

  1. v1当前

题目传送门

思路

本题是数学题。

首先选定一把钥匙与每一个门进行尝试。由于小偷不需要打开门,只需要将钥匙与门配对,所以在第 11 次时,假设小偷已经试了 m−1m-1 次都没有成功,那么最后一个门一定与当前钥匙配对。故第 11 次所需次数为 m−1m-1。

在第 22 次尝试中,这把钥匙除了可以不与最后一个门尝试,也可以不与第 11 把钥匙所配对的门尝试。故第 22 次所需次数为 m−2m-2。

以此类推,第 33 次尝试需要 m−3m-3 次,第 ii 次尝试需要 m−im-i 次。到最后的第 nn 次需要 m−nm-n 次。

不难发现这构成了一个等差数列。将 nn 个 mm 提取出,得 mnmn。然后再减去一个从 11 到 nn 的等差数列,即 n(n+1)2\frac{n(n+1)}{2}。故答案为 mn−n(n+1)2mn-\frac{n(n+1)}{2}。

注意事项

  • 不开 long long 见祖宗。

AC CODE

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
int read(){int x=0;char f=1,ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();return x*f;}

signed main(){
	int T=read();
	while(T--){
		int n=read(),m=read();
		printf("%lld\n",m*n-n*(n+1)/2);
	}
	return 0;
}
原文