现在的位置: 首页 > 综合 > 正文

UVA – 10317 Equating Equations(普通的暴力枚举 dfs枚举 c(n,m))

2018年03月17日 ⁄ 综合 ⁄ 共 1800字 ⁄ 字号 评论关闭
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <cctype>
using namespace std;
typedef long long LL;

char str[100000];
vector<char> Punct;
vector<int>  dig;
int m ;
void solve(){
  Punct.clear();
  dig.clear();
  int n=strlen(str);
  int ln=0,rn=0,now_position=0;
  for(int i=0;i<n;i++){
    if(str[i]!=' '){
      int is_negative=0;
      if(ispunct(str[i])){
        if(str[i+1]!=' '){
          is_negative=1;
        }
        else{
            Punct.push_back(str[i]);
            if(Punct.back()=='=')
                now_position = 1;
            continue;
        }
      }
      int j,num=0;
      for(j=i;j<n;j++){
        if(str[j]==' ') break;
        if(isdigit(str[j]))
          num=num*10+str[j]-'0';
      }
      if(is_negative) num=-num;
      if(!now_position){
        if(Punct.empty()||Punct.back()=='+'){
            ln++;
        } else rn++;
      }
      else {
        if(Punct.empty()||Punct.back()=='+'||Punct.back()=='='){
            rn++;
        } else ln++;
      }
      dig.push_back(num);
      i=j;
    }
  }
  m = ln;
 // cout<<Punct.size()<<endl;
}
int SUM = 0;
int vis[100];
vector<int> ans1,ans2;
void print(){
   int now_position = 0,last=1;
        for(int i=0;i<dig.size();i++){
          if(vis[i]) ans1.push_back(dig[i]);
          else ans2.push_back(dig[i]);
        }
        int s1=0,s2=0,p=0;
        for(int i=0;i<dig.size();i++){
          if(i) printf(" ");
          if(!now_position){
            if(last){
                printf("%d",ans1[s1++]);
            }
            else printf("%d",ans2[s2++]);
          }
          else {
            if(last){
                printf("%d",ans2[s2++]);
            }
            else printf("%d",ans1[s1++]);
          }
          if(i!=dig.size()-1){
          printf(" %c",Punct[p]);
          if(Punct[p]=='='){ now_position = 1; last=1;}
          else if(Punct[p]=='+') last=1;
          else last=0;
          p++;
          }
        }
        printf("\n");
}
bool fff = false;
void dfs(int i,int depth,int num){
  if(fff) return ;
  if(depth == m){
      if(num==SUM){
         print(); fff= true;
      }
      return ;
  }
  for(int j=i+1;j<dig.size()&&j+m-depth-1<dig.size();j++){
     vis[j] = 1;
     dfs(j,depth+1,num+dig[j]);
     vis[j] = 0;
  }
}
int main()
{
    while(gets(str)!=NULL){
      solve();
      SUM = 0;
      for(int i=0;i<dig.size();i++){
        SUM+=dig[i];
      }
      if(abs(SUM)%2 != 0){
          printf("no solution\n");
          continue;
      }
      ans1.clear(); ans2.clear();
      fff = false;
      SUM/=2;
      memset(vis,0,sizeof(vis));
      dfs(-1,0,0);
      if(!fff){
        printf("no solution\n");
      }
    }
    return 0;
}

抱歉!评论已关闭.