2021 5 15 16

本文探讨了如何利用巧妙的思维解决大数据问题,通过输入元素比较找到出现次数最多的元素,并分析其是否占据总数的一半。此外,还介绍了如何在最少步骤下将分布的元素聚集,以及字典序问题的全排列解决方案。这些技巧在解决计算机科学中的复杂问题时非常有用。
摘要由CSDN通过智能技术生成

一个数据很大题,单纯的暴力过不了,这里有一个很巧妙的思维,就是每输入一个元素之后就进行比较,如果元素不同删除这两个元素,最后剩下来的一定是出现次数最多的元素。

#include<bits/stdc++.h>
using namespace std;
int a[5000001];
int main()
{std::ios::sync_with_stdio(false);
	int n,m,i,lef=0,rig=0;
	cin>>n>>m;
	for(i=0;i<n;i++)
	{
		cin>>a[i];
		if(!lef)
		{
			rig=a[i];
			lef++;
		}
		else if(rig==a[i])lef++;
		else lef--;
	}
	cout<<rig<<endl;
}

这个还可以继续往下研究,比如出现次数最多的元素是否是总数的一半;

if(!rig)cout<<"no";
	int mid=n>>1;//至今没弄懂这个神奇的右移运算符,比如3的二进制11,右移一位就是吧最右边的1去掉变成1,43-》21,5-》2,就当成是/2去尾
	for(i=0,lef=0;i<n&&lef<=mid;i++)
	lef+=(a[i]==rig);//比较剩下的元素与最多是是否一样; 
     if(lef>mid)
	cout<<rig<<endl;
	else cout<<"no";

这题大致意思就是有一段路,有很多🐏分布在路上,问把这些🐏聚在一起用的最少步骤;

这个其实就是像有一个商店,商店到每家每户的距离之和最小一样,把中位数给找出来;


输入
The first line contains one integer t(1≤t≤104). Then tt test cases follow.

The first line of each test case contains one integer n(1≤n≤106).

The second line of each test case contains a string of length n, consisting of the characters '.' (empty space) and '*' (sheep) — the description of the level.

It is guaranteed that the sum of nn over all test cases does not exceed 106.
输出
For each test case output the minimum number of moves you need to make to complete the level.

输入

5
6
**.*..
5
*****
3
.*.
3
...
10
*.*...*.**

输出

1
0
0
0
9

AC代码

#include<bits/stdc++.h>
using namespace std;
#define ll long long 
int x[1000010];
int main()
{std::ios::sync_with_stdio(false);
	int t;
	cin>>t;
	while(t--)
	{
		int m;
		cin>>m;
		string a;
		cin>>a;
		int n = 0;
		for(int i = 0; i < m; i++)
		{
			if(a[i] == '*')
			{
				x[n++] = i;
			}
		}
		for(int i=0;i<n;i++)
		x[i]-=i;
		ll midx=x[(n+1)/2-1];
		ll ans=0;
		for(int i=0;i<n;i++)
		ans+=abs(midx-x[i]);
		cout<<ans<<"\n";
	}
	return 0;
}

字典序问题,这个东东主要就是用全排列函数;2629

输入

输入包括两行:第1行是元素个数n,接下来的1行是n个元素{1,2,……,n}的一个排列,当n=0时程序终止。

输出

输出数据包括一行,给出计算出的排列的字典序值,不包括多余的空格,具体请参照 output。

输入

3
1 2 3
8
2 6 4 5 8 1 7 3
0

输出

0
8227

代码

#include<bits/stdc++.h>
using namespace std;
int main()
{ 
    int n;
    while(cin>>n,n)
    {
    	int tt[9],dd[9],i,sum=0,k=0;
    	for(i=0;i<n;i++)
    	cin>>tt[i],dd[i]=tt[i];
    	sort(dd,dd+n);
    	do{ k=0;
    		for(i=0;i<n;i++)
    		{
    			if(dd[i]==tt[i])
    			k++;
			}
			if(k==n)
			break;
			sum++;
		}while(next_permutation(dd,dd+n));
		cout<<sum<<endl;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值