zoukankan      html  css  js  c++  java
  • 蓝桥杯--完美的代价

    http://47.104.209.207/problem/old1061

    可以证明直接将头部的字母固定,而后从尾部找与其相同的字母并不会使结果变差。

    对于第i个字母,假设与之匹配的为k,他应该放置的位置是n-i-1,那么ans=k-(n-i-1)

    如果第i个字母放于其他的位置上,对于第i个字母对,ans并不会变差,而且可能会使得其他的变差。

    需要注意的是如果长度为奇数,是可以容许一个不匹配的字母的。

     1 #include<cmath>
     2 #include<iostream>
     3 #include<queue>
     4 #include<vector>
     5 #include<algorithm>
     6 using namespace std;
     7 int main(){
     8     int n,res=0;
     9     string s;
    10     cin>>n>>s;
    11     bool flag=false;
    12     for(int i=0,j=n-1;i<j;i++){
    13         for(int k=j;k>=i;k--){
    14             if(k==i){//意思就是没找到
    15                 if(n%2==0||flag){
    16                     cout<<"Impossible"<<endl;
    17                     return 0;
    18                 }
    19                 flag=true;
    20                 res+=n/2-i;
    21             }else if(s[k]==s[i]){//如果找到了
    22                 for(int l=k;l<j;l++){
    23                     swap(s[l],s[l+1]);
    24                     res++;
    25                 }
    26                 j--;
    27                 break;
    28             }
    29         }
    30     }
    31     cout<<res;
    32     return 0;
    33 }
  • 相关阅读:
    监听器
    过滤器
    连接池与分页
    jdbc优化
    jdbc入门
    web开发mysql基础
    自定义标签
    jsp基础
    会话管理入门
    19. Remove Nth Node From End of List C++删除链表的倒数第N个节点
  • 原文地址:https://www.cnblogs.com/greenofyu/p/14441978.html
Copyright © 2011-2022 走看看