UVA 1592 DataBase

优化技巧:

将字符串映射成数字,方便存储也加快比较速度(配合map的find函数)

#include<stdio.h>
#include<iostream>
#include<cstdlib>
#include<string.h>
#include<algorithm>
#include<unordered_map>
#include<map>
#include<vector>
using namespace std;
unordered_map<int,int>article[10001];//(没啥用了) article[i][j]代表第i行j列的字符串(所映射的数字)
unordered_map<string,int>word;//保存一下将字符串映射成数字的结果
int idx;
int n,m;
int have_ans=0;
int a[10001][11];
bool solve(int i,int j);
struct nodes
{
	int x,y;
	bool operator < (const nodes &temp) const
	{
//		if(x==temp.x&&y==temp.y) return false;
//		if(x==temp.x)
//		{
//			return y<temp.y;
//		}
//		return x<temp.x;
		return x<temp.x||(x==temp.x&&y<temp.y);
		
	}
};
void operate_str(const string &str,int row)//将一整行的字符分开.并把字符串映射
{
	if(have_ans)return ;
	
	string line;//储存一个格
	int column=1;
	for(int i=0;str[i];i++)
	{
		if(str[i]==',')
		{
			
			if(word.find(line)==word.end())
			{
				word[line]=++idx;
			}
			article[row][column]=word[line];
			
			a[row][column]=word[line];
			line.clear();
			column++;
		}
		else
		{
			line.push_back(str[i]);
		}
	}
	
}
void solve()//先确定两列,寻找是否有两行,他们对应的元素相同
{
	
	
	
	for(int c1=1;c1<=m;c1++)
	{
		for(int c2=c1+1;c2<=m;c2++)
		{
            map<nodes,int> t;//把同一列下的两个元素储存起来
			for(int r1=1;r1<=n;r1++)
			{
				nodes p={a[r1][c1],a[r1][c2]};
				//printf("%d -%d,%d %d-%d,%d\n",a[r1][c1],r1,c1,a[r1][c2],r1,c2);
				if(t.find(p)!=t.end())
				{
					
					have_ans=1;
					printf("NO\n");
					printf("%d %d\n%d %d\n",t[p],r1,c1,c2);
					return;
				}
				t[p]=r1;
			}
			t.clear();
		}
	}
}
void init()
{
	have_ans=0;
	idx=0;
}
int main()
{
	//freopen("uva1592.txt","r",stdin);
	//freopen("uva1592-out.txt","w",stdout);
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		getchar();
		init();
		
		for(int i=1;i<=n;i++)
		{
			string str;
			getline(cin,str);
			
			str.push_back(',');
			operate_str(str,i);		
		}
		solve();
		if(have_ans)
		{
			//printf("NO\n");
			//printf("%d %d\n%d %d\n",ans.r1,ans.r2,ans.c1,ans.c2);
		}
		else
		{
			printf("YES\n");
		}
		
	}
	return 0;
}

posted @ 2022-09-17 19:35  LZH_03  阅读(17)  评论(0编辑  收藏  举报