zoukankan      html  css  js  c++  java
  • D. Binary String To Subsequences(队列)(贪心)

    题意:你被给予了一个二进制字符串包含n个零和n个一。你的任务是分割这个字符串为最小的数量的子串,使得这些子串为'010101...'或者'101010...',输出每个字符属于的字符串编号。

    分析:一开始想的是,字符个数为o(n),应该是一个线性的时间复杂度或者是o(nlogn)的时间复杂度,如果当前字符是'0',就查看是否之前存在过一个被分割的子串的结尾是'1',有的话就立马接上去,'0'的话也同理,如果接上去,那么就变成了一个新的末尾是相反字符的新子串,比如之前已经分割过一个'101',我们只能把'0'接在这个新子串的结尾,那么就变成'1010',产生了一个末尾是0的新子串的状态,原先的状态没了,暗示我们可以用队列处理,我们用pos记录第i个字符属于的字符串编号,扫描一遍每个字符,查看是否队列中存在和当前字符相反的末尾字符的子串,如果存在,那么就把当前字符的编号置为这个子串相同的编号。

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <queue>
    #include <algorithm>
    
    using namespace std;
    const int N = 200005;
    char str[N];
    int pos[N];
    int main()
    {
    	int t;
    	scanf("%d", &t);
    
    	while (t--)
    	{
    		int n;
    		scanf("%d", &n);
    
    		scanf("%s", str + 1);
    		//01
    		queue<int> q1, q2;
    
    		int id = 0;
    		for (int i = 1; i <= n; ++i)
    		{
    			if (str[i] == '0')
    			{
    				if (q2.size() != 0)
    				{
    					int t = q2.front();
    					q2.pop();
    					pos[i] = pos[t];
    					q1.push(i);
    				}
    				else
    				{
    					pos[i] = ++id;
    					q1.push(i);
    				}
    			}
    			else
    			{
    				if (q1.size() != 0)
    				{
    					int t = q1.front();
    					q1.pop();
    					pos[i] = pos[t];
    					q2.push(i);
    				}
    				else
    				{
    					pos[i] = ++id;
    					q2.push(i);
    				}
    			}
    		}
    
    		printf("%d
    ", id);
    
    		for (int i = 1; i <= n; ++i)
    			printf("%d ", pos[i]);
    		puts("");
    	}
    
    	return 0;
    }
    
  • 相关阅读:
    变量与基本数据类型的练习
    04-各数据类型的常用操作
    常用函数
    03-python流程控制
    02-Python输入输出及运算符
    02-补充:逻辑运算符
    线程
    tcp实现并发效果
    生产消费者作业
    作业4.22
  • 原文地址:https://www.cnblogs.com/pixel-Teee/p/13444081.html
Copyright © 2011-2022 走看看