首页 > 试题广场 >

黑白卡片

[编程题]黑白卡片
  • 热度指数:3177 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
牛牛有n张卡片排成一个序列.每张卡片一面是黑色的,另一面是白色的。初始状态的时候有些卡片是黑色朝上,有些卡片是白色朝上。牛牛现在想要把一些卡片翻过来,得到一种交替排列的形式,即每对相邻卡片的颜色都是不一样的。牛牛想知道最少需要翻转多少张卡片可以变成交替排列的形式。

输入描述:
输入包括一个字符串S,字符串长度length(3 ≤ length ≤ 50),其中只包含'W'和'B'两种字符串,分别表示白色和黑色。整个字符串表示卡片序列的初始状态。


输出描述:
输出一个整数,表示牛牛最多需要翻转的次数。
示例1

输入

BBBW

输出

1
由题意得,要得到交替排列形式,只有BWBWBW....或者WBWBWB...两种可能。
只需要用两个变量记录得到这两种形式串所需要的步数即可,输出最小值

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String line = scanner.next();
        int b = 0, w = 0;
        for(int i=0, len = line.length();i<len;i++){
            char c = line.charAt(i);
            if((i&1)==0){
                if(c=='W') b++;
                else  w++;
            }else{
                if(c=='W') w++;
                else b++;
            }
        }
        System.out.println(Math.min(b, w));
    }
}

发表于 2017-06-17 09:30:00 回复(13)
#include<stdio.h>
intmain(){
 
chara[50];
    intcount = 0;
    scanf("%s",a);
    if(sizeof(a)/2<3|| sizeof(a)/2>50){
        printf("ERROR");
        return0;
    }
    inti = 0;
    intwCount1 = 0;
    intwCount2 = 0;
 
    while(a[i] != '\0'){
         
        if(i % 2== 0) {
            if(a[i] == 'W') {
                wCount1++;
            }
        } else{
            if(a[i] == 'W') {
                wCount2++;
            }
        }
        i++;
         
    }
    intwFlag = (wCount1 > wCount2 ? wCount1 : wCount2) > ((i - wCount1) > (i - wCount2) ? (i - wCount1) : (i - wCount2)) ? 1: 0;
    intflag = 1;
    if(wFlag) {
        flag = wCount1 > wCount2 ? 1: 0;
    } else{
        flag = (i - wCount1) > (i - wCount2) ? 1: 0;
    }
    intj = 0;
    while(a[j] != '\0') {
        if(flag) {
            if(wFlag) {
                if(j % 2== 0&& a[j] == 'B') {
                    count++;
                } elseif(j % 2!= 0&& a[j] == 'W') {
                    count++;
                }
            } else{
                if(j % 2== 0&& a[j] == 'W') {
                    count++;
                } elseif(j % 2!= 0&& a[j] == 'B') {
                    count++;
                }
            }
        } else{
            if(wFlag) {
                if(j % 2!= 0&& a[j] == 'B') {
                    count++;
                } elseif(j % 2== 0&& a[j] == 'W') {
                    count++;
                }
            } else{
                if(j % 2!= 0&& a[j] == 'W') {
                    count++;
                } elseif(j % 2== 0&& a[j] == 'B') {
                    count++;
                }
            }
        }
        j++;
    }
     
    printf("%d",count);
return0;
}

发表于 2017-07-29 19:39:44 回复(0)

#include <iostream>

#include <string>

using namespace std;

int main( int argc, const char * argv[]) {

    

    string str;

    int length;

    int count1 = 0;

    int count2 = 0;

    

    cin >>str;

    length = ( int )str. length ();

    

    

    if (length < 3 || length > 50){

        cout <<0<< endl ;

        return 0;

    }

    

    for ( int i=0; i<length; i++) {

        if (i%2 == 0) {

            if (str[ i ] != 'B') {

                count1++;

            } else {

                count2++;

            }

        } else {

            if (str[ i ] != 'W') {

                count1++;

            } else {

                count2++;

            }

        }

    }

    

    if (count1 > count2) {

        cout <<count2<< endl ;

    } else {

        cout <<count1<< endl ;

    }

    

    return 0;

}

发表于 2017-06-17 15:53:12 回复(0)
第1个字符决定后面字符,所以可以假设第一个为W,遍历求出答案,再假设第一个为B,遍历更新答案即可。
#include<bits/stdc++.h>
typedeflonglongll;
usingnamespacestd;
constintinf = 0x3f3f3f3f;
constll INF = (ll)inf*inf;
constintmaxn = 55;
 
intmain()
{
    string str;cin>>str;
    intlen=str.size();
    string t=str;
    intcnt=0;
    for(inti=1;i<len;i++){
        if(str[i]==str[i-1]){
            if(str[i-1]=='B')str[i]='W';
            elsestr[i]='B';
            cnt++;
        }
    }
    intMin=cnt;
    cnt=1;
    if(t[0]=='W')t[0]='B';
    elset[0]='W';
    for(inti=1;i<len;i++){
        if(t[i]==t[i-1]){
            if(t[i-1]=='B')t[i]='W';
            elset[i]='B';
            cnt++;
        }
    }
    Min=min(Min,cnt);
    cout<<Min<<endl;
 
 
    return0;
}

发表于 2018-03-19 23:32:26 回复(0)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String string = "";
        while ((string = bufferedReader.readLine()) != null) {
            System.out.println(getMaxBlackWhiteCounts(string));
        }
    }

    public static int getMaxBlackWhiteCounts(String string) {
        int countBW = 0;
        int countWB = 0;
        char[] chars = string.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char current = chars[i];
            if (i % 2 == 0) {
                if (current == 'B') {
                    continue;
                } else {
                    countBW++;
                }
            } else {
                if (current == 'W') {
                    continue;
                } else {
                    countBW++;
                }

            }

        }
        for (int i = 0; i < chars.length; i++) {
            char current = chars[i];
            if (i % 2 == 0) {
                if (current == 'W') {
                    continue;
                } else {
                    countWB++;
                }
            } else {
                if (current == 'B') {
                    continue;
                } else {
                    countWB++;
                }

            }

        }
        return Math.min(countBW, countWB);
    }


}
人笨代码多,但是我觉得这个够清楚。。
发表于 2018-03-19 20:49:06 回复(0)
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int cnt(string x,string y){
    int res=0;
    for(int i=0;i<x.length();i++)
        if(x[i]!=y[i]) res++;
    return res;
}
int main(){
    string x,s1="B",s2="W";
    cin>>x;
    for(int i=1;i<x.length();i++)
        s1+=(s1[i-1]=='B'?'W':'B'),
        s2+=(s2[i-1]=='B'?'W':'B');
    printf("%d\n",min(cnt(x,s1),cnt(x,s2)));
}

发表于 2017-11-11 00:30:13 回复(0)
import java.util.Scanner;

public class Main{
public static void main(String[] args) {
int b = 0;
int w = 0;
Scanner scanner = new Scanner(System.in);
String s= scanner.next();
scanner.close();
for(int i= 0,len =s.length();i<len;i++){
char c =s.charAt(i);
if(i%2 == 0){
if(c=='B'){
w++;
}else{
b++;
}
}else{
if(c=='B'){
b++;
}else{
w++;
}
}
}
System.out.print(Math.min(b,w));
}
}
借鉴的上一楼的,不过他第一个if判断条件错了
编辑于 2017-07-03 19:51:41 回复(0)
考虑最后排序只有BW和WB两种情况,比较两种情况交换的次数即可
#include <iostream>
using  namespace std;
intmain(){
    string str;
    cin>>str;
    intcont=str.length();
    if(cont<3||cont>50||cont==0)
    {return0;}
    intcount_1=0;
    intcount_2=0;
            for(inti=0; i<cont; i++){   
                if(i%2==0&&str[i]!= 'B'){ 
                    count_1++; 
                }elseif(i%2!=0&&str[i]!='W'){ 
                    count_1++;} 
                } 
             
            for(inti=0; i<cont; i++){   
                 if(i%2==0&&str[i]!= 'W'){ 
                    count_2++; 
                }elseif(i%2!=0&&str[i]!='B'){ 
                    count_2++;} 
                } 
             
    if(count_1<count_2)
    {cout<<count_1;}
    else{cout<<count_2;}
}
编辑于 2017-06-22 16:04:46 回复(0)
import java.util.Scanner;

public class Practice3 {     public static void main(String[] args) {         // TODO Auto-generated method stub         Scanner sc = new Scanner(System.in);                  while(sc.hasNext()) {             String str = sc.next();             System.out.println(function1(str));         }     }
     
//要得到交替排列形式,只有BWBWBW....或者WBWBWB...两种可能。
//只需要用两个变量记录得到这两种形式串所需要的步数即可,输出最小值
    static int function1(String str) {              char c[] = str.toCharArray();         char c1[] = new char[100],c2[] = new char[100];         int count1 = 0;         int count2 = 0;         int count;         for(int i = 0;i < c.length;i++) {             c1[i] = i%2 == 0 ? 'W' : 'B';             c1[i] = i%2 == 0 ? 'B' : 'W';         }                  for(int i = 0;i < c.length;i++) {             if(c[i] != c1[i]) {                 count1++;             }             if(c[i] != c2[i]) {                 count2++;             }         }         count = Math.min(count1, count2);                  return count;     } }

发表于 2018-05-04 14:14:50 回复(0)
//根据最高票的答案,先生成“BWBWBW。。。”和“WBWBWB。。。”,再与原字符串进行比较
//测试过,能用
#include <iostream>
#include <string>

using namespace std;

string create(string str, int n)
{
    string::iterator pStr;
    
    n--;
    while(n--)
    {
                //先输入一个空字符
        str.push_back('?');
                //string的长度变化了,原来的迭代器需要更新
        pStr = str.end();
        
        if(*(pStr - 2) == 'B')
        {
            *(pStr - 1) = 'W';
        }
        else
        {
            *(pStr - 1) = 'B';
        }
    }
    
    return str;
}

int fun(string str)
{
    int cnt1 = 0, cnt2 = 0;
    int n = str.size();
    
    string str1, str2;
    string::iterator pStr1, pStr2; 
    
    str1.push_back('B');
    str2.push_back('W');
    
    str1 = create(str1, n);
    str2 = create(str2, n);
    
    pStr1 = str.begin();
    pStr2 = str1.begin();
    while(pStr1 != str.end())
    {
        if(*pStr1 != *pStr2)
        {
            cnt1++;
        }
        
        pStr1++;
        pStr2++;
    }
    
    pStr1 = str.begin();
    pStr2 = str2.begin();
    while(pStr1 != str.end())
    {
        if(*pStr1 != *pStr2)
        {
            cnt2++;
        }
        
        pStr1++;
        pStr2++;
    }
    
    if(cnt1 < cnt2)
    {
        return cnt1;
    }
    else
    {
        return cnt2;
    }
}

int main(int argc, char * argv[])
{
    string str;
    
    cin >> str;
    
    cout << fun(str) << endl;
    
    return 0;
}

发表于 2018-04-17 16:00:23 回复(0)
#include <iostream>
#include <string>
using namespace std;
int main()
{
     string str1;
     getline(cin,str1,'\n');
     int b = 0;
     int w = 0;    
     for(int i=0;i<str1.length();i++)
     {                      
            if(((i%2==0) && (str1[i]!='W') ) || ( (i%2!=0) && (str1[i]!='B') ) )
            {
                b++;
            }           
            if(((i%2==0) && (str1[i]!='B') ) || ( (i%2!=0) && (str1[i]!='W') ) )
            {
                w++;
            }     
    }
    
    cout<<(w>b?b:w)<<endl;
    cin.get();
    return 0;
}
发表于 2018-04-08 19:05:27 回复(0)
#include<iostream>
#include<string>
using namespace std;
int main(){
    string str;
    cin>>str;
    int count = 0;
    for(size_t i = 0;(i+1)<str.size();i++){
        if(str[i]==str[i+1]){
            if(str[i+1]=='B'){
                str[i+1]='W';
            }
            else {
                str[i+1]='B';
            }
            count++;
        }
    }
    int n = str.size();
    if(n-count>count){
        cout<<count<<endl;
    }
    else cout<<n-count<<endl;
    return 0;
}
发表于 2017-09-14 17:46:58 回复(0)
//两种情况bwbwbw或者wbwbwb
#include <iostream>
#include <string>
using namespace std;
  
int main()
{
    string arr;
    getline(cin, arr, '\n');
      
    int len = arr.size();
    int count1 = 0;
    int count2 = 0;
    for(int i=0; i < len; i++)
    {
        if(i%2 == 0)
            {
            if(arr[i] != 'B')
                count1++;
            else
                count2++;
        }
        else
        {
            if(arr[i] != 'W')
                count1++;
            else
                count2++;
        }
    }
    if(count1 > count2)
        cout<<count2<<endl;
    else
         cout<<count1<<endl;
     return 0;
}


发表于 2017-08-28 18:21:03 回复(0)
两种情况
#include<iostream>
#include<string>
using namespace std;
 
intmain()
{
    string s_in;
    while(getline(cin,s_in))
    {
        string s_out1 = s_in;
        string s_out2 = s_in;
        intcount =0;
        intcountm = 0;
        for(inti=0; i<s_in.size(); i=i+2)
        {
            s_out1[i] = 'B';
            s_out2[i] = 'W';
        }
        for(inti=1; i<s_in.size(); i=i+2)
        {
            s_out1[i] = 'W';
            s_out2[i] = 'B';
        }
        for(inti=0; i<s_in.size(); i++)
        {
            if(s_in[i] != s_out1[i])
                count++;
            if(s_in[i] != s_out2[i])
                countm++;
        }
        cout<<(count<countm?count:countm)<<endl;
    }
    return0;
}

发表于 2017-08-27 18:59:27 回复(0)
 import java.util.Scanner;

public class Main1 {
    public static void main(String[] args) {
        //获取输入
        Scanner scanner = new Scanner(System.in);
        //读取字符串
        String value = scanner.nextLine();
        //记录反转次数
        int max = 0;
        //偶数位置为黑色的个数
        int evenBlack = 0;
        //偶数位置为白色的个数
        int evenWhite = 0;
        //奇数位置为白色的个数
        int oddWhite = 0;
        //奇数位置为黑色的个数
        int oddBlack = 0;

        for (int i = 0; i < value.length(); i++) {
            if ((i % 2 == 0) && (value.charAt(i) == 'W')) {
                evenWhite++;
                continue;
            }
            if ((i % 2 == 0) && (value.charAt(i) == 'B')) {
                evenBlack++;
                continue;
            }
            if ((i % 2 == 1) && (value.charAt(i) == 'W')) {
                oddWhite++;
                continue;
            }
            if ((i % 2 == 1) && (value.charAt(i) == 'B')) {
                oddBlack++;
                continue;
            }
        }
        //包含两个战略
        //分别是将偶数位置的黑色换为白色,奇数位置的白色换为黑色
        int temp1 = evenBlack + oddWhite;
        //将奇数位置的黑色换为白色,偶数位置的白色换为黑色
        int temp2 = evenWhite + oddBlack;
        System.out.println(temp1 > temp2 ? temp2 : temp1);
    }
}
发表于 2017-08-20 13:58:24 回复(0)
import java.util.*;
public class Main{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
     Scanner s=new Scanner(System.in);
     while(s.hasNext()){
         String line = s.nextLine();
         int EventWhite=0,EventBlack=0,OddWhite=0,OddBlack=0;  //分别表示偶数白黑,奇数白黑;
         for(int i=0, len = line.length();i<len;i++){
             char c = line.charAt(i);
             /*
              *将对应改成WBWB或者BWBW的最小次数即可;
              */
             if((i%2)==0){
                 if(c=='W') EventWhite++;
                 else EventBlack++;
             }else{
                 if(c=='W') OddWhite++;
                 else OddBlack++;
             }
         }
         int res=(EventWhite+OddBlack>EventBlack+OddWhite)?EventBlack+OddWhite:EventWhite+OddBlack;
         System.out.println(res);
     }
     s.close();
	}

}


发表于 2017-08-13 19:11:33 回复(0)
import java.util.Scanner;
public class Main {
    public static void main(String args[]) {
    	Scanner scanner = new Scanner(System.in);
    	String str = scanner.next();
    	int wsl = 0;
    	int bsl = 0;
    	int count;
    	for(int i = 0; i < str.length(); i++) {
        	int s = i % 2;
        	if(s == 0 && str.charAt(i)!= 'W') {
            	wsl++;
        	}
        	if(s != 0 && str.charAt(i) != 'B'){
            	wsl++;
        	}
        	if(s == 0 && str.charAt(i) != 'B'){
            	bsl++;
        	}
        	if(s != 0 && str.charAt(i) != 'W'){
            	bsl++;
        	}
        
    	}
    	count = Math.min(wsl, bsl);
    	System.out.println(count);
   }
}
发表于 2017-07-30 14:59:15 回复(0)
package main

import (
"bufio"
"fmt"
"log"
"os"
"strings"
)

func main() {
inputReader := bufio.NewReader(os.Stdin)
inputData, _ := inputReader.ReadString('\n')
inputDataByte := []byte(strings.TrimSpace(inputData))
if len(inputData) < 3 || len(inputData) > 50 {
log.Fatal("params error")
return
}
var count01 int // 用于第一种情况比较计数
var count02 int // 用于第二种情况比较计数
// 其实这个算法只要比较两次即可,一个是BWB.....和WBW...与输入字符串相同个数,谁多则选谁
for i := 0; i < len(inputDataByte); i++ {
if i%2 == 0 {
if inputDataByte[i] == 'B' {
count01++
}
} else {
if inputDataByte[i] == 'W' {
count01++
}
}
}
for i := 0; i < len(inputDataByte); i++ {
if i%2 == 0 {
if inputDataByte[i] == 'W' {
count02++
}
} else {
if inputDataByte[i] == 'B' {
count02++
}
}
}
if count01 > count02 {
fmt.Println(len(inputDataByte)-count01) //注意需要用总长度减去相同的次数才是翻转的次数
} else {
fmt.Println(len(inputDataByte)-count02)
}

}

编辑于 2017-07-27 21:18:57 回复(0)
不知道哪里错了,求大神解答下
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.next();
            int num = str.length();
            String[] str1 = str.split("");
            List<String> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            for (int i = 0; i < num; i++) {
                if (i % 2 == 0) {
                    list1.add("W");
                    list2.add("B");
                } else {
                    list1.add("B");
                    list2.add("W");
                }
            }
            int j = 0;
            int k = 0;
            for (int i = 0; i < num; i++) {
                if (str1[i].equals(list1.get(i))) {
                    j++;
                }
                if (str1[i].equals(list2.get(i))) {
                    k++;
                }
            }
        if(j<k){
            System.out.println(j);
            }else{
            System.out.println(k);
            }
 
             
        }
    }
}


您的代码已保存
答案错误:您提交的程序没有通过所有的测试用例
case通过率为90.00%

测试用例:
BWBWBWBBBBBWWWWWBBWWWBBWBBWWWWWBWBBBWWWBWWBWW

对应输出应该为:

21

你的输出为:

20
发表于 2017-07-25 22:29:51 回复(0)
两种结果“WBWBWB……”,“BWBWBW……”,检验两种结果的最短次数
x = input()
length = len(x)
l1=[]
l2=[]
for i in range(length):
    if i %2 ==1:
        l1.append('W')
        l2.append('B')
    else:
        l1.append('B')
        l2.append('W')
count1=0
count2=0
for i in range(length):
    if x[i] !=l1[i]:
        count1 +=1
    else:
        count2 +=1
print(min(count1,count2))
发表于 2017-07-20 15:20:08 回复(0)

热门推荐

通过挑战的用户

黑白卡片