zoukankan      html  css  js  c++  java
  • [古城子的房子] 贪心

    Description

    古子城街上有很多房子,它们从左到右依次为(1)(n),每两个相邻房屋之间的距离等于(1)个单位,每幢房子的颜色依次为(c1,c2,...,cn),即第(i)幢房屋的颜色为(ci)
    冬冬想要选择两幢房子(i)(j),使得(1≤i<j≤n)并且它们具有不同的颜色:(ci≠cj)。然后他将从房子(i)走到房子(j),距离为(j-i)个单位。
    冬冬喜欢逛街,因此他想选择两幢房屋之间的距离尽可能的大。

    Solution

    可以贪心,对于每种颜色只保留他的序号最小和最大的元素,然后对所有颜色进行排序,分别领令序号最小的元素为头和领序号最大的元素为尾求出两个最大值(保险起见)即得到答案

    Note

    这道题一开始很快得到思路,但是调试时出现很多问题,没有考虑到数组的初始值的处理,导致排序后不能得到正常的顺序,debug花了很多时间。

    Code

    #include<bits/stdc++.h>
    #define mem(a,b) memset(a,b,sizeof(a))
    typedef long long ll;
    typedef unsigned long long ull;
    using namespace std;
    
    struct node {
    	int pos, co;
    }minn[100000+10], maxx[100000+10];
    
    int vis[100000 + 1];
    
    inline bool cmpmin(node a, node b) {
    	if (a.co == b.co) {
    		return a.pos < b.pos;
    	}
    	return a.pos < b.pos;
    }
    
    inline bool cmpmax(node a, node b) {
    	if (a.co == b.co) {
    		return a.pos > b.pos;
    	}
    	return a.pos > b.pos;
    }
    
    int main() {
    	//freopen("test.txt", "r", stdin);
    	ios::sync_with_stdio(false);
    	cin.tie(0);
    	int N;
    	cin >> N;
    	int temp;
    	int cnt = 0;
    	for (int i = 1; i <= N; i++) {
    		cin >> temp;
    		int pos;
    		if (vis[temp] == 0) vis[temp] = ++cnt;
    		pos = vis[temp];
    		minn[pos].co = temp;
    		maxx[pos].co = temp;
    		minn[pos].pos = minn[pos].pos ? min(minn[pos].pos, i) : i;
    		maxx[pos].pos = maxx[pos].pos ? max(maxx[pos].pos, i) : i;		
    	}
    	sort(minn+1,minn+cnt+1,cmpmin);
    	sort(maxx+1,maxx+cnt+1,cmpmax);
    	int ans = 0;
    	for (int i = 1; i <= cnt; i++) {
    		if (maxx[i].co != minn[1].co) {
    			ans = abs(maxx[i].pos - minn[1].pos);
    			break;
    		}
    	}
    	for (int i = 1; i <= cnt; i++) {
    		if (minn[i].co != maxx[1].co) {
    			int temp = abs(maxx[1].pos - minn[i].pos);
    			ans = max(ans, temp);
    		}
    	}
    	cout << ans;
    	return 0;
    }
    
    
  • 相关阅读:
    软件工程 2016.6.28 日报
    软件工程课程总结
    工大助手--项目总结
    工大助手--加权平均分计算
    工大助手--数据查询
    7.5
    7月4日日报
    7.3日报
    6.30日报
    6.29.日报
  • 原文地址:https://www.cnblogs.com/ez4zzw/p/12595761.html
Copyright © 2011-2022 走看看