【USACO2021 Lonely Photo】題解


題目

Farmer John has recently acquired N new cows (3≤N≤5×105), each of whose breed is either Guernsey or Holstein.

The cows are currently standing in a line, and Farmer John wants take a photo of every sequence of three or more consecutive cows. However, he doesn't want to take a photo in which there is exactly one cow whose breed is Guernsey or exactly one cow whose breed is Holstein --- he reckons this singular cow would feel isolated and self-conscious. After taking a photo of every sequence of three or more cows, he throws out all of these so-called "lonely" photos, in which there is exactly one Guernsey or exactly one Holstein.

Given the lineup of cows, please help Farmer John determine how many lonely photos he will throw out. Two photos are different if they start or end at different cows in the lineup.

Farmer John 最近購入了 N 頭新的奶牛(3≤N≤5×105),每頭奶牛的品種是更賽牛(Guernsey)或荷斯坦牛(Holstein)之一。

奶牛目前排成一排,Farmer John 想要為每個連續不少於三頭奶牛的序列拍攝一張照片。 然而,他不想拍攝這樣的照片,其中只有一頭牛的品種是更賽牛,或者只有一頭牛的品種是荷斯坦牛——他認為這頭奇特的牛會感到孤立和不自然。 在為每個連續不少於三頭奶牛的序列拍攝了一張照片后,他把所有「孤獨的」照片,即其中只有一頭更賽牛或荷斯坦奶牛的照片,都扔掉了。

給定奶牛的排列方式,請幫助 Farmer John 求出他會扔掉多少張孤獨的照片。如果兩張照片以不同的奶牛開始或結束,則認為它們是不同的。

思路

我們可以考慮每一頭奶牛作為孤獨的奶牛對照片數量的貢獻。

於是我們可以預處理每只奶牛向左和向右與自己不同種類奶牛的連續長度,最后統計即可。

總結

對於此類題目,我們可以對每只奶牛分別考慮對答案的貢獻,通過預處理來求出答案。

Code

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define N 500010
int n, m, i, j, k; 
int l[N], r[N], ans; 
char a[N]; 

signed main()
{
	scanf("%d%s", &n, a+1); 
	for(i=1, k=0; i<=n; ++i)
		if(a[i]==a[i-1]) l[i]=0, ++k; 
		else l[i]=k, k=1; 
	for(i=n, k=0; i>=1; --i)
	{
		if(a[i]==a[i+1]) r[i]=0, ++k; 
		else r[i]=k, k=1; 
	}
	for(i=1; i<=n; ++i)
	{
		if(l[i]&&r[i]) ans+=l[i]*r[i]; 
		if(l[i]>=2) ans+=l[i]-1; 
		if(r[i]>=2) ans+=r[i]-1; 
	}
	printf("%lld", ans); 
	return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM